Subversion Repositories shark

Compare Revisions

Ignore whitespace Rev 1623 → Rev 1624

/advdemos/branches/advdemos/cbs_ft/cbs_ft.c
0,0 → 1,811
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@hartik.sssup.it>
*
* Authors : Marco Caccamo and Paolo Gai
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: cbs_ft.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
This file contains the server CBS_FT
 
Read CBS_FT.h for further details.
 
**/
 
/*
* Copyright (C) 2000 Marco Caccamo and Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#include "cbs_ft.h"
 
/*+ Status used in the level +*/
#define CBS_FT_IDLE APER_STATUS_BASE /*+ waiting the activation +*/
#define CBS_FT_ZOMBIE APER_STATUS_BASE+1 /*+ waiting the period end +*/
 
/* structure of an element of the capacity queue */
struct cap_queue {
int cap;
struct timespec dead;
struct cap_queue *next;
};
 
/*+ the level redefinition for the CBS_FT level +*/
typedef struct {
level_des l; /*+ the standard level descriptor +*/
 
/* The wcet are stored in the task descriptor, but we need
an array for the deadlines. We can't use the timespec_priority
field because it is used by the master level!!!...
Notice that however the use of the timespec_priority field
does not cause any problem... */
 
struct timespec cbs_ft_dline[MAX_PROC]; /*+ CBS_FT deadlines +*/
 
TIME period[MAX_PROC]; /*+ CBS_FT activation period +*/
 
 
int maxcap[MAX_PROC]; /* amount of capacity reserved to a primary+backup
couple */
PID backup[MAX_PROC]; /* Backup task pointers, defined for primary tasks */
 
char CP[MAX_PROC]; /* checkpoint flag */
char P_or_B[MAX_PROC]; /* Type of task: PRIMARY or BACKUP */
 
struct timespec reactivation_time[MAX_PROC];
/*+ the time at witch the reactivation timer is post +*/
 
int reactivation_timer[MAX_PROC]; /*+ the recativation timer +*/
 
struct cap_queue *queue; /* pointer to the spare capacity queue */
 
int flags; /*+ the init flags... +*/
 
bandwidth_t U; /*+ the used bandwidth by the server +*/
 
int idle; /* the idle flag... */
struct timespec start_idle; /*gives the start time of the last idle period */
LEVEL scheduling_level;
 
} CBS_FT_level_des;
 
 
 
/* insert a capacity in the queue capacity ordering by deadline */
 
static int c_insert(struct timespec dead, int cap, struct cap_queue **que,
PID p)
{
struct cap_queue *prev, *n, *new;
 
prev = NULL;
n = *que;
 
while ((n != NULL) &&
!TIMESPEC_A_LT_B(&dead, &n->dead)) {
prev = n;
n = n->next;
}
 
new = (struct cap_queue *)kern_alloc(sizeof(struct cap_queue));
if (new == NULL) {
kern_printf("\nNew cash_queue element failed\n");
kern_raise(XINVALID_TASK, p);
return -1;
}
new->next = NULL;
new->cap = cap;
new->dead = dead;
if (prev != NULL)
prev->next = new;
else
*que = new;
 
if (n != NULL)
new->next = n;
return 0;
 
}
 
/* extract the first element from the capacity queue */
 
int c_extractfirst(struct cap_queue **que)
{
struct cap_queue *p = *que;
 
 
if (*que == NULL) return(-1);
*que = (*que)->next;
kern_free(p, sizeof(struct cap_queue));
return(1);
}
 
/* read data of the first element from the capacity queue */
 
static void c_readfirst(struct timespec *d, int *c, struct cap_queue *que)
{
*d = que->dead;
*c = que->cap;
}
 
/* write data of the first element from the capacity queue */
 
static void c_writefirst(struct timespec dead, int cap, struct cap_queue *que)
{
que->dead = dead;
que->cap = cap;
}
 
 
static void CBS_FT_activation(CBS_FT_level_des *lev,
PID p,
struct timespec *acttime)
{
JOB_TASK_MODEL job;
int capacity;
/* This rule is used when we recharge the budget at initial task activation
and each time a new task instance must be activated */
if (TIMESPEC_A_GT_B(acttime, &lev->cbs_ft_dline[p])) {
/* we modify the deadline ... */
TIMESPEC_ASSIGN(&lev->cbs_ft_dline[p], acttime);
}
 
if (proc_table[p].avail_time > 0)
proc_table[p].avail_time = 0;
 
 
/* A spare capacity is inserted in the capacity queue!! */
ADDUSEC2TIMESPEC(lev->period[p], &lev->cbs_ft_dline[p]);
capacity = lev->maxcap[p] - proc_table[ lev->backup[p] ].wcet;
c_insert(lev->cbs_ft_dline[p], capacity, &lev->queue, p);
/* it exploits available capacities from the capacity queue */
while (proc_table[p].avail_time < proc_table[p].wcet &&
lev->queue != NULL) {
struct timespec dead;
int cap, delta;
delta = proc_table[p].wcet - proc_table[p].avail_time;
c_readfirst(&dead, &cap, lev->queue);
if (!TIMESPEC_A_GT_B(&dead, &lev->cbs_ft_dline[p])) {
if (cap > delta) {
proc_table[p].avail_time += delta;
c_writefirst(dead, cap - delta, lev->queue);
}
else {
proc_table[p].avail_time += cap;
c_extractfirst(&lev->queue);
}
}
else
break;
}
/* If the budget is still less than 0, an exception is raised */
if (proc_table[p].avail_time <= 0) {
kern_printf("\nnegative value for the budget!\n");
kern_raise(XINVALID_TASK, p);
return;
}
 
 
/*if (p==6)
kern_printf("(act_time:%d dead:%d av_time:%d)\n",
acttime->tv_sec*1000000+
acttime->tv_nsec/1000,
lev->cbs_ft_dline[p].tv_sec*1000000+
lev->cbs_ft_dline[p].tv_nsec/1000,
proc_table[p].avail_time); */
 
 
 
 
 
#ifdef TESTG
if (starttime && p == 3) {
oldx = x;
x = ((lev->cbs_ft_dline[p].tv_sec*1000000+lev->cbs_ft_dline[p].tv_nsec/1000)/5000 - starttime) + 20;
// kern_printf("(a%d)",lev->cbs_ft_dline[p].tv_sec*1000000+lev->cbs_ft_dline[p].tv_nsec/1000);
if (oldx > x) sys_end();
if (x<640)
grx_plot(x, 15, 8);
}
#endif
 
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, lev->cbs_ft_dline[p]);
job_task_def_yesexc(job);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
}
 
 
/* this is the periodic reactivation of the task... */
static void CBS_FT_timer_reactivate(void *par)
{
PID p = (PID) par;
CBS_FT_level_des *lev;
struct timespec t;
 
lev = (CBS_FT_level_des *)level_table[proc_table[p].task_level];
 
if (proc_table[p].status == CBS_FT_IDLE) {
/* the task has finished the current activation and must be
reactivated */
/* request_time represents the time of the last instance release!! */
TIMESPEC_ASSIGN(&t, &lev->reactivation_time[p]);
/* If idle=1, then we have to discharge the capacities stored in
the capacity queue up to the length of the idle interval */
if (lev->idle == 1) {
TIME interval;
struct timespec delta;
lev->idle = 0;
SUBTIMESPEC(&t, &lev->start_idle, &delta);
/* length of the idle interval expressed in usec! */
interval = TIMESPEC2NANOSEC(&delta) / 1000;
 
/* it discharges the available capacities from the capacity queue */
while (interval > 0 && lev->queue != NULL) {
struct timespec dead;
int cap;
c_readfirst(&dead, &cap, lev->queue);
if (cap > interval) {
c_writefirst(dead, cap - interval, lev->queue);
interval = 0;
}
else {
interval -= cap;
c_extractfirst(&lev->queue);
}
}
}
 
CBS_FT_activation(lev,p,&lev->reactivation_time[p]);
 
/* Set the reactivation timer */
TIMESPEC_ASSIGN(&lev->reactivation_time[p], &lev->cbs_ft_dline[p]);
lev->reactivation_timer[p] = kern_event_post(&lev->reactivation_time[p],
CBS_FT_timer_reactivate,
(void *)p);
event_need_reschedule();
}
else {
/* this situation cannot occur */
kern_printf("\nTrying to reactivate a primary task which is not IDLE!\n");
kern_raise(XINVALID_TASK,p);
}
}
 
 
 
static void CBS_FT_avail_time_check(CBS_FT_level_des *lev, PID p)
{
/*+ if the capacity became negative the remaining computation time
is diminuished.... +*/
/* if (p==4)
kern_printf("(old dead:%d av_time:%d)\n",
lev->cbs_ft_dline[p].tv_sec*1000000+
lev->cbs_ft_dline[p].tv_nsec/1000,
proc_table[p].avail_time); */
 
 
int newcap = proc_table[p].wcet / 100 * 30;
if (newcap <= 0)
newcap = proc_table[p].wcet;
/* it exploits available capacities from the capacity queue */
while (proc_table[p].avail_time < newcap
&& lev->queue != NULL) {
struct timespec dead;
int cap, delta;
delta = newcap - proc_table[p].avail_time;
c_readfirst(&dead, &cap, lev->queue);
if (!TIMESPEC_A_GT_B(&dead, &lev->cbs_ft_dline[p])) {
if (cap > delta) {
proc_table[p].avail_time += delta;
c_writefirst(dead, cap - delta, lev->queue);
}
else {
proc_table[p].avail_time += cap;
c_extractfirst(&lev->queue);
}
}
else
break;
}
 
 
 
/*if (p==6)
kern_printf("(ATC dead:%d av_time:%d)\n",
lev->cbs_ft_dline[p].tv_sec*1000000+
lev->cbs_ft_dline[p].tv_nsec/1000,
proc_table[p].avail_time); */
 
 
/* if the budget is still empty, the backup task must be woken up.
Remind that a short chunk of primary will go ahead executing
before the task switch occurs */
if (proc_table[p].avail_time <= 0) {
lev->CP[p] = 1;
proc_table[p].avail_time += proc_table[ lev->backup[p] ].wcet;
}
 
 
/*if (p==6)
kern_printf("(ATC1 dead:%d av_time:%d)\n",
lev->cbs_ft_dline[p].tv_sec*1000000+
lev->cbs_ft_dline[p].tv_nsec/1000,
proc_table[p].avail_time); */
 
 
}
 
 
/*+ this function is called when a killed or ended task reach the
period end +*/
static void CBS_FT_timer_zombie(void *par)
{
PID p = (PID) par;
CBS_FT_level_des *lev;
 
lev = (CBS_FT_level_des *)level_table[proc_table[p].task_level];
 
/* we finally put the task in the FREE status */
proc_table[p].status = FREE;
iq_insertfirst(p,&freedesc);
 
 
/* and free the allocated bandwidth */
lev->U -= (MAX_BANDWIDTH / lev->period[p]) * (TIME)lev->maxcap[p];
}
 
static PID CBS_FT_public_scheduler(LEVEL l)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
/* it stores the actual time and set the IDLE flag in order to handle
the capacity queue discharging!!! */
lev->idle = 1;
kern_gettime(&lev->start_idle);
 
/* the CBS_FT don't schedule anything...
it's an EDF level or similar that do it! */
return NIL;
}
 
 
/* The on-line guarantee is enabled only if the appropriate flag is set... */
static int CBS_FT_public_guarantee(LEVEL l, bandwidth_t *freebandwidth)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
if (lev->flags & CBS_FT_FAILED_GUARANTEE) {
*freebandwidth = 0;
kern_printf("guarantee :garanzia fallita!!!!!!\n");
return 0;
}
else if (*freebandwidth >= lev->U) {
*freebandwidth -= lev->U;
return 1;
}
else {
kern_printf("guarantee :garanzia fallita per mancanza di banda!!!!!!\n");
kern_printf("freeband: %d request band: %d", *freebandwidth, lev->U);
return 0;
}
}
 
 
static int CBS_FT_public_create(LEVEL l, PID p, TASK_MODEL *m)
 
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
FT_TASK_MODEL *s;
 
if (m->pclass != FT_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
s = (FT_TASK_MODEL *) m;
//kern_printf("accept :FAULT TOLERANT TASK found!!!!!!\n"); */
if (!(s->type == PRIMARY && s->execP > 0 && s->budget < (int)s->period
&& s->backup != NIL)) return -1;
if (!(s->type == BACKUP && s->wcetB > 0))
return -1;
/* now we know that m is a valid model */
/* Enable budget check */
proc_table[p].control |= CONTROL_CAP;
 
proc_table[p].avail_time = 0;
NULL_TIMESPEC(&lev->cbs_ft_dline[p]);
 
 
if (s->type == PRIMARY) {
proc_table[p].wcet = (int)s->execP;
lev->period[p] = s->period;
lev->maxcap[p] = s->budget;
lev->backup[p] = s->backup;
lev->CP[p] = 0;
lev->P_or_B[p] = PRIMARY;
 
/* update the bandwidth... */
if (lev->flags & CBS_FT_ENABLE_GUARANTEE) {
bandwidth_t b;
b = (MAX_BANDWIDTH / lev->period[p]) * (TIME)lev->maxcap[p];
/* really update lev->U, checking an overflow... */
if (MAX_BANDWIDTH - lev->U > b)
lev->U += b;
else
/* The task can NOT be guaranteed (U>MAX_BANDWIDTH)...
(see EDF.c) */
lev->flags |= CBS_FT_FAILED_GUARANTEE;
}
}
else {
proc_table[p].wcet = (int)s->wcetB;
lev->P_or_B[p] = BACKUP;
 
/* Backup tasks are unkillable tasks! */
proc_table[p].control |= NO_KILL;
}
return 0; /* OK, also if the task cannot be guaranteed... */
}
 
 
static void CBS_FT_public_detach(LEVEL l, PID p)
{
/* the CBS_FT level doesn't introduce any dynamic allocated new field.
we have only to reset the NO_GUARANTEE FIELD and decrement the allocated
bandwidth */
 
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
if (lev->flags & CBS_FT_FAILED_GUARANTEE)
lev->flags &= ~CBS_FT_FAILED_GUARANTEE;
else
lev->U -= (MAX_BANDWIDTH / lev->period[p]) * (TIME)lev->maxcap[p];
}
 
 
static void CBS_FT_public_dispatch(LEVEL l, PID p, int nostop)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
}
 
static void CBS_FT_public_epilogue(LEVEL l, PID p)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
/* check if the budget is finished... */
if (proc_table[p].avail_time <= 0) {
 
/* A backup task cannot ever exhaust its budget! */
if (lev->P_or_B[p] == BACKUP) {
kern_printf("\nBACKUP wcet violation!\n");
kern_raise(XWCET_VIOLATION,p);
/* we kill the current activation */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
return;
}
 
/* we try to recharge the budget */
CBS_FT_avail_time_check(lev, p);
 
/* The budget must be greater than 0! */
if (proc_table[p].avail_time <= 0) {
kern_printf("\nBackup task starting with exhausted budget\n");
kern_raise(XINVALID_TASK, p);
lev->CP[p] = 0;
/* we kill the current activation */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
return;
}
}
/* the task returns into the ready queue by
calling the guest_epilogue... */
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
}
 
 
static void CBS_FT_public_activate(LEVEL l, PID p)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
struct timespec t;
 
kern_gettime(&t);
 
if (lev->P_or_B[p] == BACKUP) {
kern_printf("\nTrying to activate a BACKUP task!\n");
kern_raise(XINVALID_TASK, p);
}
else {
/* If idle=1, then we have to discharge the capacities stored in
the capacity queue up to the length of the idle interval */
if (lev->idle == 1) {
TIME interval;
struct timespec delta;
lev->idle = 0;
SUBTIMESPEC(&t, &lev->start_idle, &delta);
/* length of the idle interval expressed in usec! */
interval = TIMESPEC2NANOSEC(&delta) / 1000;
/* it discharge the available capacities from the capacity queue */
while (interval > 0 && lev->queue != NULL) {
struct timespec dead;
int cap;
c_readfirst(&dead, &cap, lev->queue);
if (cap > interval) {
c_writefirst(dead, cap - interval, lev->queue);
interval = 0;
}
else {
interval -= cap;
c_extractfirst(&lev->queue);
}
}
}
CBS_FT_activation(lev, p, &t);
/* Set the reactivation timer */
TIMESPEC_ASSIGN(&lev->reactivation_time[p], &lev->cbs_ft_dline[p]);
lev->reactivation_timer[p] = kern_event_post(&lev->reactivation_time[p],
CBS_FT_timer_reactivate,
(void *)p);
// kern_printf("act : %d %d |",lev->cbs_ft_dline[p].tv_nsec/1000,p);
}
}
 
static int CBS_FT_public_message(LEVEL l, PID p, void *m)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p);
 
proc_table[p].status = CBS_FT_IDLE;
 
if (lev->P_or_B[p] == PRIMARY) {
if (lev->CP[p]) {
JOB_TASK_MODEL job;
/* We have to start the backup task */
TIMESPEC_ASSIGN(&lev->cbs_ft_dline[ lev->backup[p] ],
&lev->cbs_ft_dline[p]);
proc_table[ lev->backup[p] ].avail_time = proc_table[p].avail_time;
lev->CP[p] = 0;
 
/* and, finally, we insert the backup task in the master level */
job_task_default_model(job, lev->cbs_ft_dline[p]);
job_task_def_yesexc(job);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, lev->backup[p],
(TASK_MODEL *)&job);
}
else {
/* A spare capacity is inserted in the capacity queue!! */
proc_table[p].avail_time += proc_table[ lev->backup[p] ].wcet;
if (proc_table[p].avail_time > 0) {
c_insert(lev->cbs_ft_dline[p], proc_table[p].avail_time,
&lev->queue, p);
proc_table[p].avail_time = 0;
}
}
}
else {
/* this branch is for backup tasks:
A spare capacity is inserted in the capacity queue!! */
if (proc_table[p].avail_time > 0) {
c_insert(lev->cbs_ft_dline[p], proc_table[p].avail_time,
&lev->queue, p);
proc_table[p].avail_time = 0;
}
}
 
jet_update_endcycle(); /* Update the Jet data... */
 
return 0;
}
 
 
static void CBS_FT_public_end(LEVEL l, PID p)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
/* A backup task cannot be killed, this behaviour can be modified
in a new release */
if (lev->P_or_B[p] == BACKUP) {
kern_printf("\nKilling a BACKUP task!\n");
kern_raise(XINVALID_TASK, p);
return;
}
 
/* check if the capacity becomes negative... */
/* there is a while because if the wcet is << than the system tick
we need to postpone the deadline many times */
while (proc_table[p].avail_time < 0) {
/* the CBS_FT rule for recharging the capacity */
proc_table[p].avail_time += lev->maxcap[p];
ADDUSEC2TIMESPEC(lev->period[p], &lev->cbs_ft_dline[p]);
}
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p);
 
 
/* we delete the reactivation timer */
kern_event_delete(lev->reactivation_timer[p]);
lev->reactivation_timer[p] = -1;
 
/* Finally, we post the zombie event. when the end period is reached,
the task descriptor and banwidth are freed */
proc_table[p].status = CBS_FT_ZOMBIE;
lev->reactivation_timer[p] = kern_event_post(&lev->cbs_ft_dline[p],
CBS_FT_timer_zombie,
(void *)p);
}
 
/* Registration functions */
 
/*+ Registration function:
int flags the init flags ... see CBS.h +*/
LEVEL CBS_FT_register_level(int flags, LEVEL master)
{
LEVEL l; /* the level that we register */
CBS_FT_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
printk("CBS_FT_register_level\n");
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(CBS_FT_level_des));
 
lev = (CBS_FT_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.public_scheduler = CBS_FT_public_scheduler;
 
if (flags & CBS_FT_ENABLE_GUARANTEE)
lev->l.public_guarantee = CBS_FT_public_guarantee;
else
lev->l.public_guarantee = NULL;
 
lev->l.public_create = CBS_FT_public_create;
lev->l.public_detach = CBS_FT_public_detach;
lev->l.public_end = CBS_FT_public_end;
lev->l.public_dispatch = CBS_FT_public_dispatch;
lev->l.public_epilogue = CBS_FT_public_epilogue;
lev->l.public_activate = CBS_FT_public_activate;
lev->l.public_message = CBS_FT_public_message;
 
/* fill the CBS_FT descriptor part */
for (i=0; i<MAX_PROC; i++) {
NULL_TIMESPEC(&lev->cbs_ft_dline[i]);
lev->period[i] = 0;
NULL_TIMESPEC(&lev->reactivation_time[i]);
lev->reactivation_timer[i] = -1;
lev->maxcap[i] = 0;
lev->backup[i] = NIL;
lev->CP[i] = 0;
lev->P_or_B[i] = PRIMARY;
}
 
lev->U = 0;
lev->idle = 0;
lev->queue = NULL;
lev->scheduling_level = master;
 
lev->flags = flags & 0x07;
 
return l;
}
 
 
 
bandwidth_t CBS_FT_usedbandwidth(LEVEL l)
{
CBS_FT_level_des *lev = (CBS_FT_level_des *)(level_table[l]);
 
return lev->U;
}
 
 
 
void CBS_FT_Primary_Abort()
{
PID p;
CBS_FT_level_des *lev;
 
kern_cli();
p = exec_shadow;
lev = (CBS_FT_level_des *)level_table[proc_table[p].task_level];
lev->CP[p] = 1;
kern_sti();
}
 
 
char CBS_FT_Checkpoint()
{
char f;
PID p;
CBS_FT_level_des *lev;
kern_cli();
p = exec_shadow;
lev = (CBS_FT_level_des *)level_table[proc_table[p].task_level];
f = lev->CP[p];
kern_sti();
return f;
}
/advdemos/branches/advdemos/cbs_ft/initfile.c
0,0 → 1,112
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@hartik.sssup.it>
*
* Authors : Marco caccamo and Paolo Gai
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: initfile.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
This file contains the server CBS_FT
 
Read CBS_FT.h for further details.
 
**/
 
/*
* Copyright (C) 2000 Marco Caccamo and Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include <modules/edf.h>
#include <modules/rr.h>
#include "cbs_ft.h"
#include <modules/cbs.h>
#include <modules/dummy.h>
#include <drivers/keyb.h>
#include <modules/hartport.h>
#include <modules/sem.h>
#include <modules/cabs.h>
 
/*+ system tick in us +*/
#define TICK 300
#define RRTICK 5000
 
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDF_register_level(EDF_ENABLE_ALL);
CBS_FT_register_level(CBS_FT_ENABLE_ALL, 0);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
CBS_register_level(CBS_ENABLE_ALL, 0);
dummy_register_level();
 
SEM_register_module();
CABS_register_module();
// periodic timer
return TICK;
// one-shot timer
// return 0
}
 
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
HARTPORT_init();
 
KEYB_init(NULL);
 
__call_main__(mb);
 
return (void *)0;
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
/advdemos/branches/advdemos/cbs_ft/cbs_ft.h
0,0 → 1,166
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@hartik.sssup.it>
*
* Authors : Marco Caccamo and Paolo Gai
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: cbs_ft.h,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
This file contains the server CBS_FT
 
Read CBS_FT.h for further details.
 
**/
 
/*
* Copyright (C) 2000 Marco Caccamo and Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#ifndef __CBS_FT__
#define __CBS_FT__
 
 
 
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
 
 
 
 
 
/*+ flags... +*/
#define CBS_FT_ENABLE_GUARANTEE 1 /*+ Task Guarantee enabled +*/
#define CBS_FT_ENABLE_ALL 1
 
#define CBS_FT_FAILED_GUARANTEE 8 /*+ used in the module, unsettable
in EDF_register_level... +*/
 
 
#define PRIMARY 1
#define BACKUP 2
#define FT_PCLASS 0x0700 // Nuova classe di task, quelli fault_tolerant
 
#define CBS_FT_LEVELNAME "CBSFT base"
#define CBS_FT_LEVEL_CODE 110
#define CBS_FT_LEVEL_VERSION 1
 
 
/* The Fault-Tolerant Task model extends the base task model
This model cannot be APERIODIC, only PERIODIC tasks are allowed.
A faut-tolerant application is composed by two different tasks (primary and
backup). The backup task is characterized by its WCET and its type (BACKUP).
The primary task must define the task period, its average execution time
(used as sort of prediction in order to recharge the budget using the
capacity cash queue!), the budget (budget / period = U that is, the
bandwidth assigned to the fault-tolerant application), its type (PRIMARY)
and finally the PID of the corresponding backup task. */
typedef struct {
TASK_MODEL t;
TIME wcetB; // WCET of the backup job (BACKUP TASK ONLY)
 
TIME execP; // average exec. time of the primary job (PRIMARY TASK ONLY)
 
TIME period; // period of the fault-tolerant task (PRIMARY TASK ONLY)
 
int budget; // amount of guaranteed capacity (PRIMARY TASK ONLY)
 
char type; // PRIMARY or BACKUP
 
PID backup; // (PRIMARY TASK ONLY)
} FT_TASK_MODEL;
 
 
#define ft_task_default_model(m) \
task_default_model((m).t,FT_PCLASS), \
(m).period = 0, \
(m).wcetB = 0, \
(m).execP = 0, \
(m).budget = 0, \
(m).type = BACKUP, \
(m).backup = NIL
 
#define ft_task_def_level(m,l) task_def_level((m).t,l)
#define ft_task_def_arg(m,a) task_def_arg((m).t,a)
#define ft_task_def_stack(m,s) task_def_stack((m).t,s)
#define ft_task_def_stackaddr(m,s) task_def_stackaddr((m).t,s)
#define ft_task_def_usemath(m) task_def_usemath((m).t)
#define ft_task_def_ctrl_jet(m) task_def_ctrl_jet((m).t)
#define ft_task_def_group(m,g) task_def_group((m).t,g)
#define ft_task_def_period(m,o) (m).period = (o)
#define ft_task_def_budget(m,o) (m).budget = (o)
#define ft_task_def_backup(m) (m).type = BACKUP
#define ft_task_def_primary(m) (m).type = PRIMARY
#define ft_task_def_backup_task(m,b) (m).backup = b
#define ft_task_def_backup_wcet(m,b) (m).wcetB = b
#define ft_task_def_primary_exec(m,b) (m).execP = b
 
/************************************************************************/
LEVEL CBS_FT_register_level(int flags, LEVEL master);
 
 
bandwidth_t CBS_FT_usedbandwidth(LEVEL l);
 
 
 
/* This function notifies to a primary task that the task itself has to
suspend its execution (the task has to suspend itself with a
task_endcycle() */
char CBS_FT_Checkpoint(void);
 
 
 
/* This function sets the checkpoint flag! hence, at the next checkpoint,
that is:
 
if (CBS_FT_Checkpoint()) {
task_endcycle();
continue;
}
 
the primary task will suspend itself switching to the backup task */
void CBS_FT_Primary_Abort(void);
 
/***************************************************************************/
 
 
 
 
#endif
/advdemos/branches/advdemos/cbs_ft/prova.c
0,0 → 1,429
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@hartik.sssup.it>
*
* Authors : Marco Caccamo and Paolo Gai
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: prova.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
testcash.c
test for the CASH Module, directly derived from Test Number 13 (D)
 
**/
 
/*
* Copyright (C) 2000 Marco Caccamo and Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#include <modules/edf.h>
#include "cbs_ft.h"
#include <math.h>
#include <stdlib.h>
 
#define ASTER_LIM 60
#define DISPLAY_MAX 15
 
#define STAT_Y 9
 
#define INPUT 0.5
 
 
 
#define MAX_STAT 10000
#define RVAL 1
#define XVAL 2
#define DVAL 3
 
 
struct statistic {
TIME r_time;
TIME ex_time;
long dead_post;
};
 
 
 
struct statistic stat[MAX_STAT];
TIME val[MAX_STAT];
 
int n_stat = 0;
 
TASK hard_aster1p(void)
{
int i;
int y = 1;
int load1,j;
 
char s[2];
 
s[0] = 'P'; s[1] = 0;
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 20000; //+ rand() % 25000;
for (j=0; j<load1; j++) {
if (CBS_FT_Checkpoint())
break;
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(1, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK hard_aster1b(void)
{
int i;
int y = 1;
 
int load1,j;
 
char s[2];
 
s[0] = 'B'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 20000;// + rand()%4000;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(1, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK hard_aster2p(void)
{
int i;
int y = 3;
 
int load1,j;
 
char s[2];
 
s[0] = 'P'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 20000 + rand() % 20000;
for (j=0; j<load1; j++) {
if (CBS_FT_Checkpoint())
break;
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(5, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
TASK hard_aster2b(void)
{
int i;
int y = 3;
 
int load1,j;
 
char s[2];
 
s[0] = 'T'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 20000;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(5, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK clock()
{
int s = 0, m = 0;
 
while(1) {
printf_xy(62,1,WHITE,"%2d:%2d",m,s);
printf_xy(62,2,WHITE,"Utot=%12u",MAX_BANDWIDTH);
printf_xy(62,3,WHITE,"Uedf=%12u",EDF_usedbandwidth(0));
printf_xy(62,4,WHITE,"Ucbs=%12u",CBS_FT_usedbandwidth(1));
task_endcycle();
if (++s > 59) {
s = 0;
m++;
}
printf_xy(62,1,WHITE,"%2d:%2d",m,s);
printf_xy(62,2,WHITE,"Utot=%12u",MAX_BANDWIDTH);
printf_xy(62,3,WHITE,"Uedf=%12u",EDF_usedbandwidth(0));
printf_xy(62,4,WHITE,"Ucbs=%12u",CBS_FT_usedbandwidth(1));
task_endcycle();
}
}
 
 
 
/* we consider the first ASTER_MAX + 2 tasks from the PID 2
and plot on the screen the elapsed times... */
TASK jetcontrol()
{
int i; /* a counter */
TIME sum, max, curr, last[5];
int nact;
int j; /* the elements set by jet_gettable */
PID p;
 
 
kern_cli();
printf_xy(0,STAT_Y,WHITE,"PID ³ Mean T.³ Max T. ³ N.A. ³ Curr. ³ Last1 ³ Last2 ³ Last3 ³ Last4 ³ Last5");
kern_sti();
 
for (;;) {
for (i=0,p=0; i<DISPLAY_MAX+5 && p<MAX_PROC; p++) {
if (jet_getstat(p, &sum, &max, &nact, &curr) == -1) continue;
 
for (j=0; j<5; j++) last[j] = 0;
jet_gettable(p, &last[0], 5);
kern_cli();
printf_xy(0,STAT_Y+i+1,WHITE,"%-3d ³ %-6ld ³ %-6ld ³ %-4d ³ %-7ld ³ %-5ld ³ %-5ld ³ %-5ld ³ %-5ld ³ %-5ld", p, sum/(nact==0 ? 1 : nact), max,
nact, curr, last[0], last[1], last[2], last[3], last[4]);
kern_sti();
i++;
}
task_endcycle();
}
}
 
 
void save_stat(struct statistic p[], int n, char *name, int type)
{
DOS_FILE *f;
int i;
char outstring[500];
for(i = 0; i < 500; i++)
outstring[i] = '0';
f = DOS_fopen(name, "w");
if (!f) {
cprintf("Cannot open %s!!!", name);
goto end1;
}
for(i = 0; i < n; i++) {
if (type == RVAL)
val[i] = p[i].r_time;
if (type == XVAL)
val[i] = p[i].ex_time;
if (type == DVAL)
val[i] = p[i].dead_post;
}
memset(outstring, 0, 300);
sprintf(outstring, "%ld \n", (long int)n);
cprintf("%s", outstring);
DOS_fwrite(outstring, 1, strlen(outstring), f);
 
for(i = 0; i < n; i++) {
memset(outstring, 0, 300);
sprintf(outstring, "%ld %lu\n", (long int)i, val[i]);
//cprintf("%s", outstring);
DOS_fwrite(outstring, 1, strlen(outstring), f);
}
DOS_fclose(f);
end1:cprintf("OK?");
}
 
 
void result_save(void *p)
{
save_stat(stat, n_stat, "stat1.tim", RVAL);
}
 
 
void fine()
{
ll_abort(666);
}
 
int main(int argc, char **argv)
{
PID p1,p2,p3, p4, p5, p6;
 
HARD_TASK_MODEL m;
FT_TASK_MODEL ftb;
FT_TASK_MODEL ftp;
// int i;
struct timespec fineprg;
 
 
//sys_atrunlevel(result_save, NULL, RUNLEVEL_AFTER_EXIT);
srand(7);
 
hard_task_default_model(m);
hard_task_def_wcet(m,500);
hard_task_def_mit(m,500000);
hard_task_def_periodic(m);
hard_task_def_group(m,1);
hard_task_def_ctrl_jet(m);
 
 
p1 = task_create("Clock",clock,&m,NULL);
if (p1 == -1) {
perror("testhd.c(main): Could not create task <Clock> ...");
sys_end();
}
 
 
hard_task_def_wcet(m,500);
hard_task_def_periodic(m);
hard_task_def_mit(m,100000);
p2 = task_create("JetControl",jetcontrol,&m,NULL);
if (p2 == -1) {
perror("testhd.c(main): Could not create task <JetControl> ...");
sys_end();
}
 
 
ft_task_default_model(ftb);
ft_task_def_usemath(ftb);
ft_task_def_backup(ftb);
ft_task_def_ctrl_jet(ftb);
ft_task_def_backup_wcet(ftb, 7000);
 
p3 = task_create("Hard_aster1b", hard_aster1b, &ftb,NULL);
if (p3 == -1) {
perror("testhd.c(main): Could not create task <aster1b> ...");
sys_end();
}
 
ft_task_default_model(ftp);
ft_task_def_usemath(ftp);
ft_task_def_ctrl_jet(ftp);
ft_task_def_group(ftp, 1);
ft_task_def_period(ftp, 50000);
ft_task_def_budget(ftp, 15000);
ft_task_def_primary_exec(ftp, 7300);
ft_task_def_primary(ftp);
ft_task_def_backup_task(ftp, p3);
p4 = task_create("Hard_aster1p", hard_aster1p, &ftp, NULL);
if (p4 == -1) {
perror("testhd.c(main): Could not create task <aster1p> ...");
sys_end();
}
 
 
ft_task_def_backup_wcet(ftb, 6700);
 
p5 = task_create("Hard_aster2b", hard_aster2b, &ftb, NULL);
if (p5 == -1) {
perror("testhd.c(main): Could not create task <aster2b> ...");
sys_end();
}
 
 
ft_task_def_period(ftp, 100000);
ft_task_def_budget(ftp, 8000);
ft_task_def_primary_exec(ftp, 11000);
ft_task_def_backup_task(ftp, p5);
p6 = task_create("Hard_aster2p", hard_aster2p, &ftp, NULL);
if (p6 == -1) {
perror("testhd.c(main): Could not create task <aster2p> ...");
sys_end();
}
 
 
printf_xy(0,STAT_Y + 15,WHITE,"Hard asteroide PID= %-3d ",p3);
printf_xy(0,STAT_Y + 17,WHITE,"Clock PID= %-3d ",p1);
printf_xy(0,STAT_Y + 18,WHITE,"JetControl PID= %-3d ",p2);
 
task_nopreempt();
fineprg.tv_sec = 10;
fineprg.tv_nsec = 0;
kern_event_post(&fineprg,fine,NULL);
group_activate(1);
return 0;
}
 
/advdemos/branches/advdemos/cbs_ft/readme.txt
0,0 → 1,6
This Example has been made by Marco Caccamo.
 
There is not a lot of documentation available, so if you have problems please
send an e-mail to Marco ( http://gandalf.sssup.it/~caccamo/ )
 
Paolo
/advdemos/branches/advdemos/cbs_ft/makefile
0,0 → 1,17
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS= prova
 
include $(BASE)/config/example.mk
 
prova:
make -f $(SUBMAKE) APP=prova INIT= OTHEROBJS="initfile.o cbs_ft.o" OTHERINCL= SHARKOPT="__OLDCHAR__ __GRX__"
 
 
/advdemos/branches/advdemos/mesaref/test.png
0,0 → 1,373
‰PNG

+IHDRÈÈ":9ÉbKGDÿÿÿ ½§“ pHYs. . ÕtIMEÓ ÿÅ IDATxœì¼ùómÙUط֞Ît‡ï÷ûæîVOzjµf 4€(3ÉNÇ®Æ8ÓONŠ vå—üI¥R•TBœCBœªT\6B˜l™…µ‰žÇ×ݯß{ßáÞ{¦=®µòÃ}ï©5`‚ ¨ÜhÕ÷{ëÞ[ûܳÏޟ³ÖÚk¯uPDà­&ûkÂòÏüÌÏ~Ó7}ã}÷]AõÕîÔ_0yˎ·ˆ@)¿Ú½ù‹'oM°˜xžg"úWþòÖ öjŠ™ßŠ¶þ_y˂…ÀÌÌüÕîË_Dykƒ%D$ò5°¾
+ò–ë ¶ïkë«%oI°¾ _ó±¾ZòKäv ‹ˆJÉøµÖWCނƒŽ"""9ç”2"~Meýù‹ùjwàÏBP)¹m
+åk1Ò?oyëi,¹» üšƒõU”·X"p—%PJ)õV»Æ%ä-9è"€ˆÎ9­5~Íþ¹Ë[¬Û!*cŒÖú«Û›¿˜òÿƒóþÇú1øGk `Ü7¹Ó
+€œ@)û›Uà „_|¸ñµì— €òÅ÷:ßþâîúC„ PÁ~ЀH¢VÀˆ·Jî !Âz‚„PˆŒÖ,‚w¦Fö.€B`±ê+iäÎ_JRYw¦¾TGý™¯
+³ÞOÔÝs "
+@ÉÙßÔŠ²
+ÊÔN±zù¹§·7Ÿ7h꺑R
+>(EÎ9"R(Z"U
+ÄDR[hkMLT n”sÎJ(9ëF#’)•;[¦Ö¸B2o|‰DdSA"¡R ӁK­mmaS+£1„R'‘©ªª¬í©Ud Ð\i® ØJ9
+„ VZ‡ëÆ*«¢ä‹‚2†Drݶ˜eš³°(&¥QȤRäJ‰`¡"èKfÿÏ
+¬½™“7ɛ?Ò*
+ ueQ"E¡ÄiDA`ÇLY͡ԍžcĊqJžKªœA`d­8'¡âœ[/L¬B“àì£Odk•D-›V@â¶m9ykM×u)%f®*£AŽÑk*Æ؅s ç8禪÷›cÀœS¢B ,M»ŠTQ
+`Hkur¶5¦®êöÏ ¬7côfãµÿ¸7@D$% %x“zʁ)ß±–·ùRpÇxQ)Ä,̉øntïQ)lPR.¬ÂD
+ƒTUM¥0@Îe¿K–
+Bí
+˜8£«Ê#±Á„ì–m֜‘L[é
+5ÃnܬœµÊŸìòT<•“~K…D&d–£­QW(Z|Œ…8g,Ji0T$ÆbLÕ¶õ<Ï»'°TR[kš}Uk·\”qljÔ͗&½ýKj¬/‹ÝÖ7w”ŒhÄRÊ]ëFDDYC&–œ ƒòÞO>å\Yƒœ(6H9Î>(¥ *ÌD” BÐZ‹H¿ë)g\,BûŠÓ®xU öaB<=)›[7j73Û˜¹ªª‚bnË1R(…R@Î+F*¹¬W«RJˆ!ÇÄuUWm‰¾¤P‚ÏDÑÏÖVP(Ffkµ¶”RÊÙº…caUréû‘šºÑ bµʔ£¡…r,iÑuBُýj½ŽsŠ!H!%hµQPr)¹­¬Ñj³Ý8ÉRxŽá… 9¥Íé®ëºR‚ºqUs6x?Ž  ¦çP5N¡iºVˆ je•ÕŠxf‚‚¶ÎXìws!i«vÇq7)ÑõaŒR •<ù]½Ð­«£8Ѳ]TVçþT`}Š›ý§½W.ÌàŽ/tÇ~QFŽ,3e’ižÇٗR(ggµ.iö(”Ål´.”RŒˆP(ÅÛÚ óTÊ4MÖXcÌØ襤)¦ÄDܶ¾ïA Á‹à¼ f£‹Q TDؔÑ¥[…%†¼Aœ’ŸKÉе%†4ÏD4î¶J¸¶¦$M9Qaƒ`
+•Ñõªî,©œ
+°&@¥YJÊY!¬sÉÞS9D®juv6@TYh]kk›óæd·3Ö*­´Ñ
+!à4ŘÈ4Ñç¹$aîÚÖÙÚFß-¬ Œc4Ö± 6M‡Êìú‘YÖ«ƒâËöd@VÎãn¨šÖi•BúSõå0ÝýxW]ÝՈì×ØwE˜€CÊ%äbö>Ì1¦”JŠV«JcŽ³âL9aJJ ”S`&¢äý|txÂ^1d¨ªŠ™‚ÑÏû3†y†A£ò
+Å1šú\ŒB£tô¡ C)¨výˆ" pš§˜’³ÖÇ8oCôsÐÆ6m7 ãÙv×Ö5‘Œ£'A MS ©
+)öÞS!Ô*)SkیÉ07«&ÌÁƒU,‚ bʅX)]4Q™BÞöór¹œCâݘ2©
+­³µhT0úÂ,((Ä@"(Æd†$öµ[­µsÍà©[ÕsŠ4LÞԈ ÑÇ8ÇΚ£ 1ŠP5ËÕîx¢]•cÈRHXRÓê]ßǜ‡!SJ©ëLˆ‹ÔM—JÙn·Î¹ƒz(€ŠYH %ò#Kí¬ñO ֗¾Ü%ß+()¥ÄSJDB”gbHyò!Æ …r
+ ±˜â 9göˆA8Sb"@Ž!Páyž•Rû’ÖÞ97Íó¾$•Y`œF«mm,;žR?ö:f´±Àͳ @œãªªˆôœ2@KŠˆX €=ÞÌ9烃ƒ¦ZúÍF¿^™!H.‘mUK’ÍgæÌ
+­Ê‘´±ËÕ¡62‡b”b|.ÅÂ>¶]„Y!§ª^lNN6þXDT‹S?”$‰8‹Š1¹a$¥cŒ>„˜Ù9nëF”îÇÙk$U>ÇÖëP Œó¶šŽ ЅèoÛ¦Ù{K)f¡A¨äm
+d0ÛÊ{:i›ŽJلDÛd®ëåÈ܇ ´aÈ Žó\rc‹@zO¨êšõT¢@I)­í9ó¥²bçýËåMƎöʉJáE$çBˆ1–R„K
+Új;¦Pk$NÆ(¥ ¹U'3•ÅbAm¶žYŒs™‹¾l6¢Õ8Í%§ ±*ÄxôÞ: M,ºnF¥sάԨ´/d¬%m¦TI1gTi•)‚”%ø1±g9ÔÚZQz;{*Ô3dT‘yB¥@g–ÊDdÒØ6 2"²‚¢=hÕ¹Š¹”\°mÝ¢ûӁõÅhí—g9ç»ê*çœK¡Râ8îÁòއr)ÂŏۘS&gB )Ç(璓w*…™S0
+¦!¥È®29ǜ“±šJ™¦¡ª*£c.ÅÏsÓ4
+ZK&â£RègO…¶C4:َκÓÁaFŒ™mƒõ4Mû3Ÿ?wè ŸÚÖ JL%"McJ:ã¦>ZϹ€6퍛·Úv¡´žcÒAªºNbD!P)!ÆNkmm¦òڍ›G Gp·uÍC$2Z@RË ,!$Ó.O§4³ªêeT.$Ii«ØXŸ’P%Q–~j@ÅsŒJƒ©êî`í ‚³ ÑX³X.—MS˜•Ö¦­½S
+Ó<#'@ÛìbX,šÕ¥‹ÞOþ´¯—KH…<*[WÜDµZP@Œ«Û–P«œƒ1f¹\„BJ‹Å¢[,ú1Œ·¶»)Ýxé܅ 5Mg}oW hÿ°ÞG¸+w]õ/ Bw
+ªQ@H˜Hr¡˜bÌ9æäcL9©Ì£Ÿ#å)øÄäSœç¹L>¡Ì)¦¾ß¦Ñ[Aa)ª6c…Úšde
+#†’CàBV.êÎX+…„dŠ ƒ¯meZ=Ž±Bĺ®ÆœEÒ GªqÑh¸Ñ‚[]Ò¥ºfqìaÕ­¹…˜âŒº;Zn·»VE¨9<ðMM:MÞßbÊZ/¦äÒÑ;=@˜æ샤rÔvÔ4#¬§Mß×ΐˆgŒR÷ž÷ÆúiѺzšF£u1þyæ\_:P€4y¥Ûõò€D¦n=k%
+Ñâá•wsŽ³o«\cŸ¦©—S)(¡ÌFÝwoY.^öÓÄ<ÎÑ&Q¶™$Ÿ;X­zÛ­×^âeÝ‚9f¶­Œ}[¹¤øù×ßxàÝïcfÛlu2¢Öë~núpéÒúún÷ÒÞ7_¯zè¡[·n]¿~}Uw)#2.H'ÑQôåf1ª¦XkÚÏ®uzq´cëÐE\þËh¬»îÔݺõ»Á¤RJ
+)Ǻm‘­>wî܍ëoÄB³”œCœ'®ô–³qF4²”›Ó®F\¬W%Dh«ZFïmSS.§ý®ÖÖu­'Ó¶ƒŸKÝ4Ï.gý1£RvóÈ(®ivÓ¨S
+•'ÎeÕ-^+Eˆ‰|Š T1è›Úø˜GÉzÙBã"2—˜…—m­ëêO ÖÅÍîºSw=ª˜
+³¦œsˆÁ‡Sœ†qšç")ÑϳŸ}?O9 ³Ã8ÂÉ뮉)IŽ¢ÐZÛTM§“~·^­“°€”¥Ä"MÅV¢™(p±
+6U£•òeöTŠmÓ*çÆyY·ïzඪ¶ý®ŸÒMÛ®–\ˆs!æyö•s–0í|ãªÖ5n½X¶‹ÍæÌK¶UCsl–mÚ1DR˜A„Š˜§ ­vv‘| Y S·è€T µ\(†¦iÀYpFˆvó$’—‹EÈØkº«­Òu×Ã`œó9§œ˜¹ÖzêLjØ."œbŒ1èºY.”ö[Já\²6¬©l¥­æIçÜ-º8M”²Óf&©´‡jë KŽéâŋçW몪ÞvéÊf³ ™8³-,·=–9ÅÜv]eÝns¡,Ž.
+Ñà§?X{žnÇ<E˜9SÉ9çœïj¬œsfITbLsôÓ<÷ã0{ÏÌ$B(!§až‡yúq·Ù% Òj±\ÄL±p&6»ÊÚ¦²•®łœ²R­„,P¹ÊÛoz»X6u»¬ÛÆVã8ž½0¨BR
+•’KÙívÿ¿ÿûßû=ß½\.ôGôÒ¥Kÿáÿ0‹üèOüħŸ}J<@¡š÷ßøïúøw|ê³OüÿËO\Z¯ÿ³þ»GëÉÏh ù©Ÿÿ~ãñO°¾|I(w²Uö©vû (a.…r¡\(•bòÞÇï7ÛÝ4ϱ$Â0Ž»¾ÏÈ>„LT€Må|ˆ1¥ «£zÑíÂT
+Íã˜üÜTÕáúmÎÚ³ã
+ÓèCð>ö}Ï"Êê˜Ò<Ï)%öq
+^[Û¶m&PR‚×ÏNÞ؞úµ³½ŸŒµ‚ ´žü¹d*ž’[v©÷Y0 2Bˆ‰ÐtέÖk¥a±ê–Ë…s¶ŽÒ²·§ÓÉIÒZ
+BJ[¼+¾&1Ii2®R•5ÎTÚZ¥ÕÁŚH¬s ô4‡˜ÊüæÖIÉIJQ
+ã8ŽcÁY TŠŸfÜõ‚8ÞÍ%ÿí~øå×_ý…_øù¿ñWÿõ‹/l>û;ûˆÄ˜BJ¢µ5&û©ß­WTògŸüüÙv³emÈ)£¸¶a£tL)å„ZýêoüÆ÷ý›í?ü¿ý[ÆÚoyì±ÍnûÒSO^xÇP×µÄOÏNUšq6çòe%v_äc}Ñþ SþbªˆHD`a³Ùl‡~œ¦ižç9ìv;VÖøÇq )Æ~œ§©n›Æ8QYb’\6ÉRN™h·ÛicúÁLÞûœs™Jâbj'sÎ"1…ÆZM™R–ÆÙ¶ª4[2ŒI˜ã6N>QκrÐ8ö™f5)eÓ´÷8UÉSN‚Z)­³ÆYeŒ©«е‹f¢– IDAT±Ô¨.¬Wp°~Û¹óÁû·nÞ<¾sn¬n­qÆ´]§Œ9=;+1ÕuÅ,ÊÙ2û0LuUuU“­óPP´JÂèLgŒ!ˆkö[æ¥d­uL±Ÿ'VÖ`e0Î>Ŝµ«ÞñÎwV‹îc} ý ¿ôKÈÂDZéw=ú®ïüøwrçÆà_øü3¯¼üÒ}÷]ùà‡¿ážøì§ÿýïþøwÞwß½J©Ã4M1¥œs¤”³TJ;™ƒêÚèçÓí)£D.u×f¦~ ¶­Kʬ¸äœJ1•ûüÓO~{ü¾÷¿ë=æqíìG>ü‘k×®m¶Ûóðྖ$~ä‘G{ì1ªŒQæ7û·WŽþH°îRu#æ”Óݝ¾Û
+3)ƒhµÖÖ\½ïsõÒ>}íÅt—ï¹ò‘÷¼oq¸~öüó¯^{uÝtM7çøʍ7ú~èºVk[
+圸î. 목ëæá‡ßþØÇ;=;þ/ÿ»ÿö÷ÿÌ×àCÿÑßù÷¿çû¾÷þÒÏÖÎåX~ùŸ}òõWn…áú­›Û7NJHßð óËÏ>?ôۗž{á»?ñ‰«W¯þÎïüŽµÖãœ5ÕÊÜ{áÂ7}ðC
+ñ•›¯=þÔçn܈˶sJu¶úºw½7!>ùÌÓ]]G‚¦iLå2õûæ±üwέ>ôþ(¥üñw½ý* žw]HåÇÿçðýâÏéU‹¢^¼öÊ=ÝÿÀzsžÂÞäåœsÉ>„½­ !Œã8ŽãÊév»ëûÂ4 Ãv·E…óìSJژªm®\8ïªê•×^úátØ"[9J%¤˜J¶Ùp4Ð=nߐkE3ÅaRF¯ÚEÛ.ªº²ÙÇ0̛±ä„1]hË£¥±„•f+dJR‰€H
+j·«Ã£"”R  ˜Xˆ‹$³I¹ßžigÛÅâèÜÑÑáÑzyîêƒOÑ~~íÆE81¤’oÞ¸YÜ`AÍÃT×uœæWŸz®^/Cœ×M·²õåÅÁµÓ[Z› .P‘Rx»Ý¥T4B*̂ĐS)¥¼ôüKO?ûìoðÖññsÏ='ÄðŽw>²øv¹X®WK«µòó|zó8îÆ«<ô‘~ÝAÓþ{ûßR"W.\vÖ.—˺®µ6Z«¦iªº
+!Þºy³Ñö±oþÆ˽ŸyÛó_ý×R4ÇJ°f¬¬{àÂe·Ëw«`NñÚk¯ÍÃøMùèÕG}ⳟDZ†B”r.ªh…›ÍÙ /¼`Öݸ.Ýwߗ?ÇàN
+9 Q)D…8•s1Ìó<Žó<Ï)çqŽýàûÙ÷Ó´†BҐs 1ŽãÈÌm×vMsß=÷v‹…Ñú¥W^q'•C¬›ÆX3 îßqÎ {Ä^¡Ç7"t‹õásև|È2¢øƚºS®®–¬$ރÏD™™A$šŒ…}õ±Úç@µ¥TSc½h")9§B$Ä""À‚¹¢b₨4 ¦’ršæi»9{£m»ÃÕÁÁáÑѹ££Ãƒƒínwëôd˜ý'»©nÛ®=îÏ¢Åa@ã‰NŽ3SÛ4»²Ûmú76·Š…ûο­­»œ‹¦©,›•J>”œç~è§)å2õ£SFJ,M·HS
+!Žã¸ŸR*¹”” ¦¸ú¦ªœsËåòúõë¾µA"šæ*c;[Umc¨„m_bhëzÑAmœÐ̊ÎI]¥,èۏ-@©¥”VZïí 2bæ†T–êèâš1QÁ”SÉeÿäœC*6—”sN A@ˆÊ>¦Ç"‚˜¤dJq7œß8]œ¿ty}xxÏÑù£nyãÖ7óÉgnL±ˆ
+gߐA)Å̾ð4MÖZ¢¹âÔT®¶º2ŠSPh$—PŠµ¶®kT:&ãäX!†9”X4j¥´Æ"ý¶Ï¹ž;÷àƒºUsëôô¥ç_~û;®vm÷s?÷óϾøÂéØ÷›³aÿæüÀ¹váç ^:þ[>øá~žDä¥k¯\ö©º©‡q<\ÖΩÚõ9¾vzSiBa˒·Cœ£ r†át÷ùçžþà7}¤ŸÆ_|±ªêª®Ï5Ý{¯¼mÓïœ1WßõÈG¾ñËÃCDýÒõ×ë/߄އ«
+ñ~{&…C ý^Y;‡yò›Mï}Ã8ÎÓ8Ž9çív;Ž#ìŸ1Æq¯_¿NDUU3{cû”b…DSŠmëºj*wÔ­¹ÄPr.­ƒ +»lt¢™A3JÑ
+´V¦TN´VZ­µ1Zk¥Ð!(¥´ÖJ©}!†Çy€º®)»sçÏ75"ï :øn%
+1MÓ´_ÕïCŒY´² €V™T(yšç7nÞê–Ë˗ï¹péâÃ=|xîÜÍӓPò²jÀ(òiê{ç¬1V •ª’µ¼þúo¼ú†åG|Ìû‡6^¾|¹”rýúõ®[ø”±ÅwýØuÝÞË6V}ûwü¥¯ûƯ×Î\?=þ§¿øÏÞÿ®wÏ!>ðàƒ÷=üà¯üÖ¯ß|íÕ§ž|JP}Ë·~ë3Ï<3ŒãÇ>ö±÷}à“Àô~ú§?óÙÇcJÕ}÷ôÑ÷xïSH±”(”s%E‡31ÅZm¦‘ Î\>óÔ~Ûñ͗_~éÕë¯Ç’ØÏܬ–Õj Ö~ß_ù«û¶o7Z‡Rþ§ŸøñO}ö÷¿,œ¦‰™S¢˜bH)•4?NÓ®ïÇqÇi'fúišæÝØŸ—Rö F˜æ¹®ë”Ò8Ž{˜bJÎ¥”´ÖûõišêºZ¤VmsáÜ!pQ ~Pòª©N-+hŒ`IšX£å«
+y_*¨îNc8Ù¼ê¬M¡šFz÷{l+±wÒ™¥PùÂFgʹäcß÷ý®¿µócH1%F­´1Êè²R‰µuݲ{Ç;Y,—¦r>Å×®_æéôt3ûÔ¶-37MCDÞ{4°:X¤TÂäK,À€ öªhšæ‘GyßûÞÇÌO<ñÄË/<{õêÕgŸ}6Æh­}ûÓȋ×^×Õ«ßò‘æ2”Óqûò믝o*ԍ¶Ο?¼xá÷?÷Äk¯¼²lÚ˗¯„àoݺuõêÕår§éҥ˟øÄ'^»ñÆéæìÕ×^cïùÆoÆq¦ßüÌï>ñ̓fÑܺñƇ?ðÁÚUŸý½ÇEÔ#ï~×s/½ÌÀÎáÕû¼qýúÙé©kšÃ‹çÏ-V7^z…ˆºúv¬ëzÇÕzýÌË//þÓ_û"°v»ǔ}Œ>Ÿâ4MÃ8î†~†aœ*W]¾|B3MóÉÙÉgÿÌÓO?­µN)m6@¥´ÖûLŒýŠ:¦¤kçœÛW€µmÛ÷}NåÂÑÅE[/k %λSgteÕ²­ÛÚAXBe@eÀ6ƵbkÖš”ujÿ\¼ý¢[äý7ú¶¥tŠe˜oߧ'Ç?ú>g’½»4aÚë#b¦RˆIX
+û‹jWû•
+jŸLÆD€¨”á»*«”¢m[wçJÎ)MÞOó´íwǧ§›íf7g*D¨Ik´VÈ~ž‚Ÿâ4‘äÃo{ç£ëvIüY­õ}÷\yà¶ÛíµW^ñ¯Æ)%$æ¢ÓÎZ¢ßï¡Ý¼yóääd¯×«J·]ç½÷!Ló¼^¯A)ÕµÏ>÷ì Ï<cµjWmTäêzL“Óúðüù³ÓSp­‘BژåjÕ±TMKÄh”}6ìcðÑûãt#Šuî¬ß®Ž¬¶$p¸>êÓnµèÞùÐÛßÿèûžù¥'žnã{«UæÞû.7®ŠžxñY0fYwyöuÝ"h`Q
+aL0Á(BÆVǔpe‘&c\ðÀ!°ˆäÒ2Æ¥„ûG18g´1Fi¥”ÖJcP™¨²¨Ä¡ÔÕñ±æÄÄx’$+á`8èF…T€%` µªt֕yvùâ…l4šÝ·/®Õg§§‹¢èw»ép¨”ÚÜÜôú$
+Ýyìd¥ÙúÁ‹ÏäÃQ‹£söMM_\Y0EIbj²² £˜
+“Q‚cBüí‚@㜓Rú%xSí©"k(c‚Ѐ2„ ívõ`¹‰z(Bd©Ò9ËÄ0¢ s¡u3Œ1BØ9F©ßÀÁ¡xý§­
+qÁ1ÆÃáÐÙ#ŽS+‡´6Ji+Y`´2KÒ(vQTÍ+ùäXžæùÊÚÆêúæÖvßmю’4(Ïóþ(¹±²2>ޞÝ`ßԔTòҕ+›€1Å`¥¬×›wßvrj|"¥çΞÛX[¤¬UœÅÈ@ÄY-Ë0Ä(!È9)eˆl”
+e-çoVâ¤yžçy‘¤iVäIšfY6HFÃÑ0IÓÑh”ç¹Ö:I’Á`à±#_
+œMGC=FS!g¥”VËHð4I9
+ȝŽ†Œ1dÍ ÛqÕëõj½¢KF£ŸlXY‘’d˜Œ†i2LFƒÑ(Ͳa’¤I¤ÖYQ8ä8á^ŠÎ»
+sR!çZÕÚ©S'û۽ͭn¿Fá‰ûîÝ·o8.-/K«SU¾uª -v$I†Þ¶F£,Ï Y¦yšd;¬)¨(KPðû›½aÙ]7èœ ÃÐ9A¥R¯…ݍžÉ†ÍJÐ®Ä ³l”PÎaÀÄE¨Bˆ8K£]íT´;r×"»'üïu=ù“1r€•R¾VÀE῁Rš%i¯×«Õë„ÀØþK|yQ–åæææÙ³g«µxs]¿¶°oßÜì윒Ë\„¡”jyu•bR­Ö(çš8Ž £Š1RJkLEµZmb||©¾²º¾Ñë¤RÁÄ:k¬]¸~­,‹ƒ‡NO"ËC©Ô`4TZ—e©”ŠÂcìk(‹Â/ŒÁ`àóÔ$Iî¹ûîÏ|úS·ßþ6­¥ô駟þwÿîߟ¾ÿþÏ|êW>ÿùÏ?ùä“õjuvvö·~ë·þæoþF•å§?ýéÓ§OûGðòË/ÿþÿûǓ33¿ò«¿
+ÖÕ¢J£Vëw{©Ñ_ýêW·;Ýßùíߎ£(KRŒñF1üêŸý9ÕöŸýÆo´ÆZñø㹒„ÅŅ×ΝÿØ÷ÑÇ>úÑååå?ÿòŸŸ9wöãìxÄ{Ùõõõ?ý/ÿùåó¯NLM½%yOÓ,/¼£ò¬âþpP*Y;ñ‘(i­‚ck­–Ú»(¯ë;žÑl69çQQBòؚͅ V³Z**–ˆRǘlœ¶Èa„bÞ®º¹ƒÑx¼Ó²ÖA µÎË 9çb´§´æ½·ïÌʲ4ÆpÎcBð"/ŒÑ”Rkʽ¾¡^­ÅÝn×Çn\8‡BHáP\©
+Æ)〳ç™,2ã
+!AIGÈ9Áh†ÕJeaqy}cSj²Za¨”¼~õrž%·Ývg½Ö:2³}k´¦£’PĐô¾|ö…—ƒCyÙjµú裏¾ãí§¿üÕ¯\¾|ù§úƒþéŸùîßÿývg«V­<øÀéüþ÷ŒVï~×;§&'—ßóîw}ô#ù¾ðê™3¼óþЇÏ]¿òý§žúŸ~¡Q©~äg=0³ïñ¯üå•õÕs¯¾zôð‘ãǎýýßyùŗ8çe€¶ÖWÎ˜žh·Ûí>ò¿ûÎÖU`Í{ßó®±FM9§Ôé{ïý…Ç{öÙçžxâ‰|òé½ï|ç…Ë—ÞªÝM‹¢È²l8%YšæY’¦£$QZeE‘æY)wUD00ÁÁa)¥ŸøàcJyž{t2ŽcŸ"l÷{#‰ âÕ¥2”`*"Ë+@Àb§AÈ
+F°ÅVÛðvvÃrJ&¾aî÷ïsÎc9BJkg­Ú}ûÜjy÷5„·6Ƙ±ÆGY(oX¾CàE¶Š¢˜™™ñù™CŽx,µ
+£øȑc”-rŽA8̲¼‡³ss ’…Ö†RJ ‹ãj­V£xmks˜$c£ÁXpÖïu_yþ…ãGN=v̔2äÂ*¹Ôk<ùëñ·Ž Q…Ÿ£aŒ‡qßqÇÝ­­o~ó7nÜȲôÓŒµ~ðýï¿üÒK÷Ý{×ÖÖ>øS?õ쏟¹qýÚÏü1¥äW¾òå¥ÅÅ4Ïî½ûîÉ©É4Mo¤×:¢Š2¥g_9óò¥ JëÛNž€žþ™§¤µÆ`{}óøþƒƒþ`iqiöðÁ—_ziiii0èŸ:qrvzæÉxò¾{ïéw:'Ž?ØûÆã?ýôÓ333§Ž¯×j”ÒŸ
+³"Ïó¼ÌËd˜Ã</­qE^–y)ˆV&£$g8p”h
+
+‡©2Žñ°ÑÀJJ¥JÎc4Ã@0.è…ËW–ÖÖ­A4 µ¡4O¯\¾¤­9vüTµv‡Öv©Ó¢ÁXg4
+œµÆ¡ ”:甔aåiöŸ¿ôgþåÌïþÎï\½péÚõë—®7šæ õÜ />÷ ìコgŸ}öüÅK˜³'¾÷ä¡£G~ïwïþò_ÿÕ¥×(F›gŸ}îêå+ŒÀäÄ8— cJ(rî¡÷¾÷£iÀ/_½º¾¾îRZ½~፠ïø}_ÿö߶[c÷¿ýí?þÑ3ÃáЧ§ßûþ÷oûë¯}ⱏaø¹Ï}nkk ( bñVå:Ó$ FÃá(KÓÁp¨–Jù’ÕGw«˜¶sk@BXçXTêÁ–È2ÄdœÜZí4‚ A„ì]pÈù"ðæÁ½pvsšsÀçCžX’e™OãªÕj2¥iÒ¨7¼ì-c””þ
++•ŠÁ^òç¥=.ìCg’$£dT‰ãÑh4>ޞ˜h{˜ƒ‚€X FkB@©’|åê¥çž{îðþùWϞŸœ8|ô8••5]µ8ŠE5Ž"ƨ·zG@90¾ÙÝÖÎ
+ ÚY«e·»%µn6Æö˜?x`N9×ÙÞÖ ƒ àŒ”eYJGdIB†³ö̙3ÿößü›O|ì±Gzˆ ñÔ³Ï\½r•Á ?øñ³?þÐïþ.#øsÿå˪,ãV}m»ó•¿úK+õϼÿ‘#‡áϾôÔs/@·Óéoo÷kíh4rÖæyN)!&&ڙ,c½ññ( BQQJøÃ~øÑGï¾ýŽÉ‰‰}“S_ûê_ÆQèBollüɟüÉÖÖÖ'éo;uêñÇÿΓßMµ4Zÿ„ä=I³Ñh”eiQ–eQhc´5ތ|=¿‡)XcŠ¢ ”ªReQ‰ã0 ãjXäIÑïUmryŽÓ@„%@(ÂØ9ì[¿;CFö4'½áúÄÈ>`{ÀŒ1&„ð¹Ñp8œœœ¬T«Eš:çâ(΋!Ê9”繧."C»IL­^"°Öë¤I"K)ZÍÞhûèÔd£Ñ4|÷Ð!ŒEÆ9gýþK/½EA¯½öÚCÓSqQR.¯¬4ªÕj­æ8JET œ;tèhT©_¸tiayQM „(F£~ïüùWµQcã탳³`,ãüÐÑ#ýÁàÒÕËëkëÎÚfkl~ÿ~Œq–eN—`üú… ÿößþï/<óÜ/}ò—þég?{c}õêâb†Þ…ôºýÍÍJ­&µnOMNMO_¹|Y§ù±ãÇÿÇßüôÿûÓ'¾û$‚`†¡‡ñ8ù`(¥,
+ùÕ¯þåwžü{ˆRÊÍ­­#‡y2Ï /¼ðéÏ|æŸýÚo0Ɯ±W¯\¹çž{†0
+½ç´ì-êHÞ¦õneŽ1Ã!4”RzZEE¾í]E)%c<‚jµºof_E> 5Í0 0x¸ÕB’4Å;ë¬ucããƒsΫ•]5çÔYC)¾~ýêöööá#777§gfŽ=*„À0ÆkO0.&Â0Šƒ¨DÕ0ªNOO;rhßD›ƒÅβ X2ì-\¿6ì÷ZµÚ¡¹¹GßuÇíGªÕ*ˆ"#u»ÕºÿÞûÞ~ïýãͱf½þ ÿùN?¦é_í¯¿ø¥/ÍÏÏ¿ï}SBŠ<ïm÷úýÞõ7Ö×× @@èƒ÷Ýúžûdš÷»ßýãÿôŸ²ï~Ï»cmñhÙn£‚`L„‹‹‹—.]^\XØØÜôëÜ×I‹‹‹K7ÌÌÎÏÌ^zýÂúúz^äA¥Z}ä‘G>ö±Åqü /üÁüÁÕk×Þ÷ðÃSZ©7V–eišùñy–yõ<Ï}õça·‹æYcsÎX‚q­ZmÔêQ&›$ÏÇy#„µ!£17@q`rvLÊ7ÿÞH´ß;$»û}JäeÇιá`À9ã(Ë2C„/)¡µ@í‰öØØ£ÔƒòŒqB‰w¢ŒeYÊk)­ !1Æ!‡‚;°kk«çοZ«Wü­xÇ;lµZžû%„Ø7»¯ÞlaÊDsE ˜ÆÕZ­ÖŒâJ(¢}ÓÓ·8¾f&
+˜µÚÍ£ÃAïúÕ+ùh0^¯úýþàôÌÓ[Û[q5²Ö úƒ…ë7®\¾ÜítãŸøùO¼ï}—E‘§é…¢,i–YçF£Q–eI’ † 8æÁƒwÜslÿo~ýëßþö·Ïžus0 ”ùŒÅ_¶WoÑFSεVÞÇSƲÑHkí9>2t»Ý_|±WBÆ/_¸˜¥YžÆÙþpp÷ÝwÿÚ¯ý¥4I’­N§»½Mõ*o…eYyžE^¥’VÊCŽQy?á‘$„5Öû³3ÆÒ4M·»û[cUB@„aiµ2Ȳx7w~f8ðg·÷òVå;ŒØ ƒ1ñd˜½¦‡¢V«Y>%ã­±(Š†ƒ¡R2ŽãZ­^«Õ ”!çŒÆ„E Á„%µÑ†`W9¥$Ëó¨5›MOXÃÚZd0%œÒ¥âÜùsW¯^¾í¶S/¿üÒCï|ߝwÞ%æ„…bŒZ‹*•j‚'¤ÛݼtõÚüì¾F«%Ôæ¬G0£(8x”–eRt1`UËI–å*“§O?
+‡C')¥ ¡A §íf½‰Îújˆ6%Ô8l1ŒÎ4Ãغ½„éæAnviö?¸Ñû-ßøÛíî¯rAǔsÎ9ˆ‚0
+CŒ€Q¡¯þöܸ5®Uo8œ"„Ö–“óç®>ðàµz…à€P»ÕYþ‡ï~ç=ï~øöÛîæ"
+“áµk—Y(*µÆôD»74êµ¢(5„p‚±µÈ"”¤ép4²ÎY^«×Â(ocÆV¥\\XˆÃh~~¾Ùl@háFgs“267³o¬Ù £hu}-Ësk,¦D½¾¹á¬ã(G2+Ëë 7œsI‘úý½ùhmap n§ãœ ÂÐÏÖ[\\dœ,,• ‡ªÈ©8ça#Æ¡ðÕÕ­™>|tyyyc}ͽoß¾æÃ0Èó¼ÓëöFC„¡,K„6ȉ0¨V¢F­Jê4«
+Ν£`‹±%ÔŠ0~ *¼q’ÅŽŒé-©:Ú¥Ìã[fÍ{[ñ¿eŒ…aìšŸVê1Û,#„øñIADQT‰«Œ¥2ÆØæú@It×Ý·sN­A„¢K—^p'ŽŸTÊPʃ Ü!í"v„Âæ榵6KÓµµ‡zøè±ãJaƘwicÎ9£t»³ùÝï~§ÛÝ<tèÀ¹ógûýíÇȲ\\Z€z½n¬#˜"k¬Ra3!zý~2J1`Æ(!$/ò²(ÚãíƒTãJW†Ã¡*ËF£~èÀýs³adEfBxTªÕ¬ÌOÝ~ûô¾™~¯Õkõûî¹÷h·Ö·6G£¤R©œ8yâ®;ïäœoúÛýžEŽrAY…”Q)­)¥åLJɁ…qä*dY©V¥ÒžÌsò,&@œq–2F/eéâa@«Ök¿þØ'Þà±——:Ý-­Ê²(֖â8J³¬,
+ ¢0§<
+ZkÀöر£ss³/¾øbµZ?pਖØ!ä¯Á·öcÝNç©ïÿ·«—/ž<y|yé§À¼øÂsûff£(ˆã<¤˜ck±³8ËggfzýÑ(ɤÖÖYB vv4äÉpß䝷Ÿ8ùÌùsëë+E6Š?uòØÄÄę3g¶û=©‡ªÔq[䔔Ú%•/ž´Ö¾ˆ»²p½ÛïQÎJ)—–ª•êúÚZQ–Rëjµê5Ã@\‰ó¢ˆâØST€¶†NœC˜¼(Š²dœ‘(¹ËŒÀÄ9WJé{š!ã,`àœ ñ¢ßØD[Z…9¤iª¤”à ƒ8®‹
+XCÐé÷9 ˆq¢u±°F#Ä&  7Z•^{¾ÚqW·Hb|³íC›¯–ý¬s˜ǘRÊÃ)ó•¿RÊ7<2¢”´cËRyø-IÓR&ZÙ^o;IFss3”±j•eYfìV½^÷j`8§F㡇J’ŒQÎY¨åN)îÿ¢•••ïý·'_|þ™'Nlm¬¥Ùèرcׯ_ÍÓôÔ©“íñ BøhY‹ id6Æ:‹êǏɊâÚÂB©
+¬‰ÃIé§Z; À:d-´Ã#ö³Ówf¹»QøÝÙêàv:„;cэ1;ÌvÓ)B<Üï‘'ŸÖ8çœuFk­´sÎGÇ0³,óô
+Ÿœc)ÃHQH„0 „ ¡Îé,ϬƒJ¥@*Õ
+çÜh4€jµš%iQ–QaB¡J¥šçYY¨Rë 
+G܂$
+·mUÛ[ÝËK÷øٜs?ãJ…s!8wÛ] ¶Åã1Ãï<uÛäÄdÐßÞ\W²ôÁÔRbÀ9£µCˆX·orúm'N½¶puqqcƱgJ¶ÆƓ$µÆhc‘µ­Fóη½íâ•ËK뫾ÉF1Ás.´Ö¥”µ·i*Ë2ŽâãGOÔjÕ8Ž¥Tׯ_;{öl^J„ Æ~–
+¸(‹Â”9,õù6"`á&QÁÝba·Ê-Çšƒ·V‚o0£7ŽìñOÚˍ„aèi¢J)ç\-ˆBAÝiœsc,ޝíÝ^QªN§3 Z­6ñ”RF×66ʲtέ­­ù€ ˆ¼ÑʝsA ”Œ¢x~~¾ÛédY:¿ÿ@¯ß«µw¿ç½§n»=ÍKʘE9«µbŒíß¿!T©ÔŒ2¥Âi–u»ÝííN½Z9yüØ(KÖFçIrãê•Ûî¼ëøÜ|«:Üàp%®­7×7oìŒéðTf¥ÔÑ£GO>:ÕßX_ÿþÓ?Ô2?4à»ï/Šâå—^~핳gµÖZ’žos!„ön5g4Ïrì‚b0<|ààïüöoýÑ¿°²²â­OÕÓ41Z2ŠU)‘ss³ÓŸúÔ'¿ù­o­|㛜2ÊÙh8„(!J*Â(coIÞw–©R ì2ÆjÃ0IµF…B¨RÖ+Õz­:ô‰E•0b±nðçÀÛÖN#v?I‰!|‹ay—»ð­†å¬»kùUèWí^õw«ÁyÕóîÓ4B`LŒ5>ý÷`U¿ß[]]õ†%¥¤„æy¾µ²|ùê•V«577çõŒ1¾Ãè»=WÁ(ÅZ­Ö»Þõ®(àO<ñÄÜÜ\·Û)‹òÑþ̱ã'¥6"K©³ˆ‘’eQÚheÌV§síڕÁö6B&-òúXkÿìÌÆښ4š2á,²a%
+ëͱQoxñÕW;ýa§ßKŠd/ÑÜÉ;•VZaÀZë~¿ßëõH$Æyš¥iÚÛÞÞÜÜôgË\©¥¿ >§”ÚRɲ ŒRY¥§&¦}#د՝%Z–#«£„S
+Ύµš¡~§"Žã¼(œ¶žþV‹RJGÉè™ÿXk=J¯¾åon%Šf¦&9œmkt‘¦€a‚¤6Æ @Ú:Ë ØÜ»¶µWúÝ
+doC‡WŒã
+Î:gQb»ßO’Q«Õäœk­Ò4á<à"Ø©@€µ†bA %kµ³oàYZj‹0ÂþÚ)ÁÎÖÅ ¯]¿vuksSp…õn·såÒåæاÜY7&£A_k7>>GÑܾýëë[/_±Æ`ÂØh0ÜÚܜ™;8¿ŸÖâÅÕegœW+‹ÒiË0µÎi0ŽJ9„¬±ã@pJÈÔd»ÝžÖèÍÍõ²,uÖ:J(cœbR˜YÀË¢¸ôúë/½üÒCïyçâÂÂÕ+W<×HpþÈûßOéOÿtfjúSŸú•‡zèGO?…!Âä[_ý‹Jµúé_ûÌõ…ë_üâ«õ:ç¢tá7 §RJ!¸.KF ‚ `B˜çœÃP–e{[í¤MdÁ·)²˜`†ܬ r»=BB|n׏sÈYoÈZ„‘·0çސHì@Ö"laì,RÖ0
+Pj8‚’”±\J£”*ˆC[ Dð´¿æ IDATÊòâÙó¯J«Ód„•EÞjµ†ƒþË/¿ôŠ³£Œ`Çq„E^üð™g¾ö_¿Fûð£>zä0#$ä\–’p
+GËËˍññ²(ªÕj½ž­­¬:ʵ£´EB@ ­1Îƽá€2vpÿü‘C‡0ÆÏ?ÿü~ô#ßÐ *‘1¦Ÿç€\½Vkc‡[ŒQ«Q
+Y pÛm·—eÙïõg÷Í<x0MSBˆ¢þ¾Ñ°(¥A$ƒ~V”˜RŒU¦Ýž8tàÐx³q¶²p-ív¨3BØ!ì:övÖü„ãͶ…CœÛÁEÁC¨·¤VþÄX‹oæì7wÙc¼£áy2”ÒSJ `R(ä=­”µ~©…ÕªÊò¬(‹‹—//.¯X+…²@Y{jº^kDa ”PB5e,pgiêIϞƒw70îYó^‚„ÜZ»´´øõ¯?Þl<x`ksmey©Ùl>|xeeåƍûöí ÃðƍBˆ±±1_óSJ‘!AÈTW*•™™™åÕÕÁ`Àãŀ777××72g˲lT+e£&8oÔq
+.œµÖš0Š[ãcVsemuqi)͒íAŸ2ÊRmm‡Áh%n6ª!¦&&õºT
+0PJ‹,ç˜Ô+Õ©É)Np½R½ûλöïß¿°¸0?ü¡÷{ÛÿëÿùÎÿõÿò¯çææz.c¬W&Ûmk]œ‹£‡mÍJw3K~ÒX¹"/@$„l´‚7*ՙÉÉöØx™%Vi
+G‰Vöêå+ýno¬Ùrªì®¯… 3Á|*tÓª;ð>l—Íþ˺ùln>ßÕq€œÏè1Dêr;Ÿ¸ rbŒ½XƒÇu¼~Ä “@0ᜋ@XÊnc½»²¼Þï+ÕPÊ´(ˀq‡°”zqi™&”2*D€1„a(„hµÆؽmû{&µ§°p‹aYB€FÑ}÷ݳ´tcyeißôôö֖7¯V«µ¼¼Üjµ~øáƒ×ëõ~¿? ¼|&e!Ä9sªÕêìììòÊÊvš˜Bb‡2 ¼Q¯U«E‘W+xØïk¥¨W—#D+¹º²²¹µÉ¸ˆÃpnv¶Óë'IâKÂ,Ëc„àj7ëuU*«5ˆÂÐÇ)Ӕ:c àPFðÝwÝÙjµœ³ý^ÿëßøÆ¥K—{ì±0‡ª×ë~ Ǐ?öя58ŒÎ¾r&£~ðƒŒóþ7Ó«kKozþ$k!g)BBJiJi¥ZwÎ1ÆCYZfI#Ž9%Èh Ôbì ÀÎÿC?ÉctÓcíþƒv†€ý „áÖ÷x›th—•µ÷%€œïäøîÍÖÖÖææf?+”ÑcL å<Šã 0re¡”2EQ¶Ûc"dZ+„€ ±ov?c¼”
+tªß}ïk_=~2Ÿ­âÒݹs÷;ßùÎÙٙÖÚ:n¬ˆP1€³6iêêZIH7,†§‡'÷>$3
+¬›j=½ü胯e.泺©ƒ"Ë. Ëx~û®µ6ÏC]5•«¼”8îììóíF€ç|?ïé$eF!`nŒYÌ˲ö!H¢³£ã~ž}õìñÿ?ÿ»Öé;wHŠ'ϟMó/_>ü?¾:;:Šâ±!xdøë¿ÿŸ_=}º)«ª*Mcnœßúów“ Û“7 @&R9ëLðˆ˜·Ui½ÓZ“ I¬´ Þ *ä½ú^äé]Ï Îèĉâ
+ÐN±â)‰<ïnéîv»”„BB`Œ«ê¦¬() BLÆ£;wîܽ{7²>Œ1„8î{Öpµ)/^<Ët‘& 2ƒñx49š4Ö1¢gOÎ"K2­Uš&ñ¨íLêÊAgaà™£Ü¼s¡×¾ÿþGWW¶.¿õ­o}ôÑGÃᰭӑŠœsÀÌDÎ9•¦¤ÔÚù‘„ÄŸNŽs7¦‰01³¯6kÅAªd%•I‚EWm«Çϟ?{vñübFÈ£á@'R’ˆÖ{-Ež$"¢€LZ§yVx‚` ÌUÝ̗ËiY{R%³,˲T%j¶˜'B…jg¿|úxºX£aY×eYåyá}+fë/ž¼x~1ŸoÖ%eÖëé,…`ºq¿§¯g…Ƙª©PRäˆn6›~¿ppp0KBޚºÙV ‚øºªÈï»øuºßÄkÀÝסCS»ø,bWËåz:ŸyïIIçBQÿéƒ?ú³o'B1ðê÷ûyži)½Cï0ÍsÇÁ«$aæ^¯‡DuÓÈDÇò‹Ú±¾ªªZ­V/^¼˜L&´”Û7/Ø{I‘ÔÖµnÇžžžþàÿeØËNOO1‹Å"jïØQPkµ.//§ÓËÓ“B
+qrrrzzòðÑ£ˆç!bY–ëõúp4ÖZk„Mc®®®æ‹…±Ülø捳Û7o¨D†à˜G ÄYDyžçY_s|8ëõz:¡„÷aµZ‹üèð Y¾|ñl¾^>}ñbUm
+!„çù»w•À²®Mc„P.0{Ç( ÆìñúüóÏg³«¯øáx0”BJ!-Ñh4ºuûöWÇ¿kvÓ«éÑá$I7u$"‘: Î5Ö¸àن¼HT’$iª“$±¶$Ė=B,†FU°º®“aî¼3ƗˆBÈóósáÙô
+´äT-êreëUµ=>>î
+OON‹¢X­V•õÞÏfÓ(š%¥ŒNa“êTé„=ÇF!j‘«èn£ü3a,TÄ~n­u¯ß¯ëÚ5Gãq–èÒÚÍvë9yÞ+
+‡Ãxu³{ûb㼑‹ j­a·­ãïú(­ÀŒ™H¶Ÿ~ú駟~ºÝn[çŠÛ_ É[…03‚^¯;!„¨ÊjµZ‡ˆ-ÏGI•å¨śí6Š1xgLt$Ñ}î4Ì!úª=Ÿ
+Ƙ¦nØ9 \WՋç/`·nßÎýéjá­»œ^±q>õûu!Ñ ØÆÄÞ|!"/ášË‘eY«DZÇc£"
+µ›ÊlVh+©o‚G)3¾µ,øŠä·g6Й0¶±¥,Gÿ÷#†Ø€È ‘=âr»Ý4.Šív{÷üæûÑ_¾óÎíõjÌi‘%i"¥ŒpÌ%‡“$qÎ``bðƲs©L8ØÁ`PEt3DT7õrµÇñ迸¸ˆ°Et“boœXgî=qÇx~=¨ Ñï½ÏÒ ®®.þ¯?ý_?ûé³gÏÎÏÏÿòÏðõ¯]km=7$Œñ…ðBh”7NϾø⋦i„L¸5õ²ÚžpÀÀèC¯(jc2…ÀÌB$ ÖBpA2£sž¬³ ^%$ Ðyo90¡H”³Œ!8Ó8ÓXd\Ti‡LL«åŠëU¹Ùø²B;JZ•×€b% °õÞY‡ ®1J)ã\míIfÏשÉiš’$ãBòÎYc¥yš’II@*ïØCWï㷁 oý
+¿fU­ îútÚEzÅÒzU?Á£¤( î¼wUuxtôÃÿú_oœyë€9˳xî¼qà‘āØGtcÄÕ+zãñ¸1&B÷SA¤µöÎ/‹“““Åb‘eÙ.öUØÏLcœ´oXÑMî¿øèf¤”UY~ùèу>ýôÓËÏÇÃýÅ?øàƒ<ÏgÓ«²,=‹Ë«i¿ß?>>fĺi<30ƒ^¯·X,â
+–«UUÖ €Ù9ë9x瀄@òƙº­¥ RB 3Æ£3á­õΣ ­µ"º g€YU]͖sË¡4ÍÅŅ'PZåyî¼o¬‰“
+æ‹ùzµ‰Ób¢’s ѺøšÇ’ŠA¢$ĺtι<Ëó<G×HE"P,^ûµÿÈõBŠðÊavñ
+ì…\¯Ì‹9Äié»F€oûÛßýîwÑz½ÖZG èêÄ~7 £õùCà]¯%'JMŽ&Ãáp[–JëD)ǐ$É­[·œ51‘ŽÑn÷ÂZm€ˆ1±êx­]ØN»¦mÞUŸ¼÷=úôÓO˲ì÷ûïÝùÓóӓ££‰RÉz½Ùn·!ø2ê™o·[ï}Y–eYj%´ÖÃÁ`¹\:ïBXÍëå2ë÷”¦i‚ó‰Þ;/ ÄQ¸X* u]3s¿ßÏ"Làƒ±ÞsPDÎXkŒJ’¦ª”R’Te³6xÏ>Ô¾ª›Ú#˜¦nš&ë½¢UûýÚ×U|@€8e-²bá(v^Ä1joV–„ŒÒû „R4MÓÔ5°;ړìĺfUÐÆæ×2ˆýh&.’˜WÒí~øá·¿ýí¨Ôílÿ·âZvC ¼w»û´§Õ`0˜L&Zk"Zë˜H
+©µFàõzñåˆÙ@wv¥;õâçíMcÞ0¬.‡üq\EÈÈÁ9ï#=L43;Ï*ÑP×u üs¦.™9¥ñÎEð¹©êÍj¥´FöA
+‘¤ÚZÛ4•e‰À;cLp-&w29JoÜDĪ®MÝb@pÎXdˆ£b©”@[WÞÚ¦®Áï=
+»Ú5§ÇG¬¼­
+tç·»1ÜËó"%FÄ󸵬6à/w‡‘õ†ÁêTß}÷Öd2
+™y»ÝFì’1Íf½vBÖö.¸¶|O¢^Á®ÀŠˆDM òâk‹&ßQ·6{Ùtƒ ]”-f„,K•RÑÖ)ò
+½·Îzfä}‚P*ÚA8Á^SM–iªjï$
+Àìêª\¯µ \nÖ±;숨Èò4ÕÌ!¾6±'nà ±|×#bîÑJ"èǀǣp6›Eƒˆ‘ß?ˆ»5F$ï_cq”u¯*ŒËå2Þ?®ML"HFDŽ º`}ð!x!´1I´ŠÀ2D6|è¢i$ÑåL1Gf @¥{šÀ†LðÌ!t4'I`gÙ‹Á9R² D€’P’u–˜ƒ ò¾µJX 2®×ÛB$R(‰@€“$8•@lÒ–°'®»¬˜ÚQ‡2Ī0bK!m=0 T‚B $§d"…ÐZÇȺªê.ˆ€.¹efç< Yã¶Û²ª`R2k7ë±?”À³£ã$MƒEQ ‡Ãè"“•vÞ(Æ
+B­UG
+Àˆ´Îº°MvßbDˆ­Ðoœ'í ‚ ÁyD°{ßiµ<1HoÕ}™¼$%APpÖ9v¶aöÁû$IH\«®W%@­©+[¥Jso="N”`ŽŒ<Ž´vcî"Ö·^ûF°;1aKµ ~vö×þWU6Mð`<Ž¥È8ØKA­# q(3"9K!ðfcÊ­sbd[zcúy¶çŒ!yš•äy^–åÓ««ƒñÁÉñI¯×»l6›M§Ó4MgÓ˦i†Ãáx<®ª*΀˜ÍfϞ=»¸¸€ù|þøñãív3ÄXGÚ>ð+•€Îl)†\ØV¯ vþ©#3µŽ‡[NUçð8x@’\)4e£
+î@¿«/ŇûÊ®÷–[v×r(Bà RÆÖ/ã9
+ÌaçÀ
+=°pŽ«ÚéܽÅce遭+ÓÔÆX[7~蚦©·¥NJ‰Ÿ‘Ö+$Þw©8D’Õ[c,"ü¶ê~ÀöŠ<íVŽ(yDz„€ xâ ¥,ªÒ/æeÝ8BªÊ­‘±i›¦ … º2Æúùr¹\oUðP×õfµ°MI2U%«í:-r@2Æ̧³Ç_~y<Y†Ãêً“ÉÄ{ÿþýÓÓÓÉdrqqÙ4õh4Ún·?ÿùÏ£@RQËåòêê*_,B´*Þûñxüãÿøæ͛e¹Yo–Î9æ$IÔ@ìõúÌüøñãétöòåˋ‹ $!`YVŸ ¢¯D§(vS¥”J‚ÒIÑëYï·UÙëõ>þîÇ·o¼³¯Ž ;ZH·Ï»Ø—wÝÀ¯fÏþº/ù`«ª¬ªJ
+sH´žOySVÖº€äB¨ÊU
+ëà}ªÕj¹xçæ-[׶1:ë'Ig¤}Pó IDAT“€à‚{ùò¹ÖÉG}´Ù¬ÏÏÏÇ㑱4™6M3›M#íäìì,V~ò<¿¸¸(Ër2™D^$½üO¿÷'~øÁ|1kLåBE1 tªs³Ù¬èå³Ù|r4Q¿Q›Í˜„1ö€È’ˆU#Ú €1³dLŁ‰Dë$ÕãñøÃ?üÑ_üx0H!iGD¢6nEnÝPÏvϹEÒbô±ïÍ1@X.æ³ù÷{ƒýx£;—cÿLc­‚¤ð¬s Õj½ž?zð¦aiv¡*ÁY+<IÈD2Hó&/¤ÒÌÑ¡°(< ÙC§k°ûè¼{e,]Ê·ËØß&Þ8=¡M0#î¿Z­V‹EªõíwnþèÇßÏ´&âÉáam,Çãù|~yy‰ˆumàñ“'«õÚ±Ÿ¯–OÖª©kL"ziŠÎÖÞÛ€HÈ$ËOoÝ}õàž¤ðâù—ïÜ:…ДÛû¡RˆˆËÕÌ{r:™Ïç—/^ó~«°ÈBè÷ûBc} AeµÚ”ÓÅúEí™ê,Éb$·Ø.Ö/×e¹>½÷èѓwn¿û­¿û«_~öòéó]úF°½uþfw”)¬We<"gÍì¯ÿúï8Óþƒÿ’ë”+ `Ï!ƵƘ®l
+Áê´xï½÷>üê“O~zqq¹Ùl¨…îà•¹ì¼Tlèè(]ÆÀ;ŠlÔS$,<üÕ¯?¾÷ÇßÍó¼óX¿û|öãƒI–æeS7¶&ÈcûÝou~ñ>uSǍ÷šaÍ×KÊU’¥BUUH‚³ !PHB ÀŽƒ‡ø•aÁ®¦œ8Ê«™mT€-Š¸+3Å/wð 2‹hjB4¶Õ¶iª§OŸžŸœ zE¹)+k»6.9\\\Ü¿÷EÝԉ£A¿®¶y’ {=…D€¶m1PιífíœK¤X.æ:QiªY¥„ÀÞo7kï|š¦åfcëj³]Õuµ\®Á;¿^/Ê
+ò¼0¦vÎ:gŒ©×›UU™à="*™L&Ç7Îo‘¤ÕfÕÔÍv½ŽÂ‚Þ‡¢èFýùl©“´©~ùðށ‚ùu–N|2€pxrtttôèáCϞ™Ûj${„BãÁÁØ:3Ÿ-˜¡Z¯ÞûâäÆéÍããmUé,c±Ç=¼n¸WÀU6À¨|Fq“(©—ú`7$€:e¼·Vð¡ns]ƒ´d×ËzR·.x¯3¥E)—Ö;LH @öˆ,(0ÆIô…êD¨×·x2²BB`ÂNõ€ bµ0D,M‡¶M
+øÊUiš\\\<{úlôÁ‡‰H¶uBˆû8deY~ùè¾i¶x¯ ÆE~ûöí›G§
+…ªf€™ÖyžVeÖ4ÍhÐïùp8BɑÈÂj1÷E‘H¡
+¥SÌòžµ1FH,úí¸ò,×E/ôƒa¯¬¶ue@ràAo˜Èl:»¨Í‘”Jtšã¼÷½bH(­sÞ7‰‰àLˆ¥½7V E"oÿÁݓóÓ¯^>í \͖±C>@à¸Þ`üßxWeêù£—Oï=©·U9ŸÚ±&á)‘,fü-ñ´ð4Ân[ŒD HADXH“µMc7B°‹„‘~ø&„ADJJk®Öz½ž®Ç"yïëªÊ… )ŽÀ£6˜ÇáwaÓ[ßÃk à~ºÿOA½­qO2i%Ó4ÑÛíöòêŠ?€¼×ۘŠˆò<oš&Ò>§Óév»å=Núd2ù裏ÎÏÏcÎô´ÖY–Ÿ{ï‡Ãa4Šxpôz=DLÓÔ{oMÙ+úyž÷{cLYUiš@Ó4Ö¸ºn8@“›A¿¶†7›•÷!:§ˆ—E€Rª,-U×µq!XKDÖØBš¦Óæëë˜F£áååe–e“ãÓ¯¬_,¶ž= î÷‹ÁAÿäôèäôd0|íö¿}þÿþßÿ÷þüƍç7âëÌ<í1÷¯_ûQ
+ò ¯uŒDRk¡”ÎÒ|>Ÿs@¥ÒD¥B"E$»ÐG)Õëõ†Ã!
+v¾ººš"R‘÷­µÆØ8d/MõF
+ï}”ò²Ö^W ÞEaŒùÅ/~‘&z4Ý·Vjé­ïõzï}íÝ»ð
+ƒC‹ù|µZE¿¼¸œÏçIQôÅÁѨ7ìÉDnʕ]ÚñxœeéùûgßûÞ÷~}ïӃÃC­“È¡…À]iä-^ñµzõÝëṐq{k­V'mÿ–û˜ª~‹Td¯×WJŔØ{¼g¥”R*ÐǸ»µ—Ý!¸{it½¬ €Ñ?¦8÷±•R&"ˆŒ7)âp$)!2AHJ%ý¼·)·,D@x~ùòèÆéÑpÄ!ÄCg:>þ<„%\ò</Š¢(Š““ØSv4ÆD½
+)b¤i@„¦0v,Å7ÑÍÂB(©Ø9À"¬«˜‘&$¢މÎÚ(ý°X,['I²Z­­1ãC!¤gŠPèŠ0Ïsh“phêë֕fÙz³€?þøþoî]¾¼LS
+ûãþÁÑáp<̊t¶ºš¯æ½¢Ð;<¸}ðWõWßýÓo§µÙl³dˆˆÖ[ ,®‹ÿvÛzk¤Á¦•72Rñ®_2¶&úk¢ ·nݚW«e]‘”R¶TC!„PJ#I!‘‰BkP]Qsÿ£ˆÂÚo¾jÆMÛ©_݁ñˆ‚â(0„(ÅF”ÉÁ6ΪD-×믞<f92{ï///ïÝ»‰.wïÞí&eFºUÜ¢•Êoˆ’Åvœ>ï]ŒCŒ1°C’¼ ¥‚ƒoùBž#Ñ»à£X±$ASzæ][‡ÖZ&¦Ùáá$Ž@W*±>€àÍvñôÙÓ(?,¥Äæ-ëÙ|~|vZUeL{Q`¢“^¿7>ݼ}+ë§óù,QêÞ÷¸äÿü™Ü§÷µÝšoþ‘Šú¹R„#òw:­îöÁØÖÈâKuŽ#o‹‚–B^?´äv»f𠜤ZqÒl›ª±ŠTåüŠ›ƒŒÐ1¡P"5 ¸3Ž}ӊRîÝ{h?!äÀm]ˆARdÌ·Ýp„RäXI¡„ˆ
+“Gb%“^Ú/N‹”ò^‘-gëËÙź\s€zm./ž¾8>ô%¦B(ë\(q¯ÿeßz~¯©Å‘¦J
+†­Q`nšz7ÊÀÇÁ{ 5Ê¢(BqXµ”IUUUՌLJ<¸wïJ¤Î´w¾iç!3…¶Ì±«I€ÎÒÁ¤wûöí[·nŽÇ1Sùèÿðød2ßÿƒ÷¥ÔθAt~vûjquyyqqñìdrB°†~GßYÕïv`Ý{ïãHÇ=<2R0Ó$iú¦aA" Xßx‘$$$cEOŒÆ‡[ç¥RJ
+_Ռ,[¨öõׄ-Ü°³'l͔¨¢ˆØóÚIŒHR Ü±CD"S©¹Ü¬«ífS–B''7o£Qã‹ç//ž?zxx0V«Í`p0•e¼­kCBfE‘å}AÒïÍgYš¦i›H_÷Xaù*þØ{Ö¸«ij­csf¼[ìÒéªéÝåCˆ’Q«Õj<GPJ靑Bõ{ƒ'Ÿþò¿
+҉êÛ7ïTåçOž>šJ•z ‘7~ݤÞøø;Œ¯{Û»i¯L ®ê,Ëß4,ìkJí:¸”R¦jÖëµj¹©h[êB«H¡Œ§~Ô mƒvD±¿í B’‚ÚÚ#±@"D‰ª;‘2!’D((Q¼_¯W³éåf³rÞ{ÂM]Ý¾„Øn—Ãá`8gYV×f¹X#$išIæFÊ$ª´;¼€^1Ùy)×\Œéùu.¶Z-*þdôRñiF傪ª¢æ‡sQ
+@ !цpuuõ³Ÿýìôôô[ßú–”2Ëòí¦ÜnË{÷îÿÃ?üÏ/^23 H‹ìÎѝ¯ôõ<ϧÓé?ÿó?+™–ei¬enõÃÒ4†iš‘R`QJòŽ¥LbåLˆäð`2?šn·Ëårz0:"p oiR~êð÷U¬;Ï´OˁJ €¨ÕóšaQOK¥Biœ³ˆ”§™©Ýf³‘EŸ‘Œk|P
+/j‘'*¯êz]¯,yÔÒÏ Þùz³F¢~Þ;:™¬7U`(Mpf³±Í•Öio8TiF Øc°>˜óòž5uÝ4¤" ±±§ÓVèfÇí?bÂ×ÎÇ´Zg€!8oªj«A‘9… VœÞÿý[·ni­•RÀø䫧ŸþòWóٌ•”Þ{AiðÕã  ¬qôÎÝ;ÿ‡úgŸH©ž<y‚ ]`ë•Lc(ՅçPÕõb±l6u®ò~ÚcÌ%JoÓÃÞ¹ñÅŋT?»yC Ë ]™XûðZµ8¾ÓèÔ»”^2a\úÐÌæ——‰N‡ý‘T*QI¢u¦õÁøàMÒA¤R;Û$L(X»Y®›m•)=й P5v˜¦€€ZäH(L0'ä8ÊKÄÎ!8/””J¢ dïÆZbIJ ÷Ö90ˆèQpž€¶›í—ɼwçÝ?HtV7~[5Ö9$®Mm¬Í§Þ³:Ï{q9›)­µN]Qò‰¢Ô¥@Š¸¿N°nŸ&bt$Þ{ç\´˜<×uõôéÓØTÈišn·ï=ýŠqÁŸÅšRUU¿ùõÿþo¿¸ÿ~ð!øÐ5=gEá|˜Í‡“ãO>ù×Õ¦ú³ï|K'ɳ§OÜ¿Œãñôê*Ü ˆâ½»ï&GI¬„<<œ¨1õò{ïv…W™¢€DWýíl:-ËMU¯SÝG”bŽûÄ ùGyrû.ª{,¼w•åöùó§/_¾œLŽ&GyÞC¤PÇF£× k»XJš1T•0žkÛ`\½®2LPˆùv=,T&%¡#Dì‰bO"´ìŒ$ˆ‘&€’ŠIyð!
+­}GõÆÓ´Ö$Jᮼ^Z¿sîôôt:>~üD‰ý±ä‹¢ðRê4]­VDâêòêŸþéŸþíçÿ^×u—9J)µVU¹Mól¹œo7«“³Ó_üÛ¿¦àß}÷7/^¾¬·år¹,úE"51ŽRÎ§ó£Éñ³óLêN6"bÞ"IDy^L&“ÆTe¹•"ˆ9@
+ì "Q
+q6½œM§EÖÓy1‚ÇmYrÞ«Ëf1Ÿ%JND’DÜ¥¬ªõf¶-ËñÁ±í¶ëR›.UÞߎñiò[$kCÔ
+ã@÷”Ä·„óû}AûdA¶/;Ï{‰¾ ŒZ§DÂ;&"oÑâéW%{ï°+›8MS¥´i¬³~|p°ñMÍ!´l$µ*!’Qpû9
+@ë€ ì¬dD‰
+MÝo[¸¿GL!º–Xp”RÎÓº®G£ÑÁÁÁÓ§O«ª:<œlVkˆ‚q˜êÕÕL%iUU10 Ÿ~úë«Ë+nÇеJeÞûÈ騷›þh$õà‹{ï½ûîÇßýî¯~õ«?þøßøÆÃ{÷‹EU–?ýÉOïÞz÷ý»ïY¯ÈŠD&̾kƒæœ‹ˆÎyD,ò<I’Ùìªß_y!郏ñ%FHýÚQعÞÎ1óŽMÙ9ï]ÆÎyk}ðQ!†Bpo)!ý¶VRJï½ڑ7. õI'é[·–¹¤r…$‰‚§8Í«=
+®c »ó´=^÷žÆ«~*@%"6uÎ+%cYNì†k¼fX©”€¤uºÙn„R!PU•¨UO¥y–ŸÝ¸Ùï%³¯²ŽbÕÆX»ÞÕØÝùð„€*IP R¬& ¥U ùFæ
+… 'Ož|ýë_ÿå/¹^­ÿøÛ¼Ýnÿæoÿ&fÖØÕb¹]—ä… ‘´§V¾&¢Ì(¥’RXç‚E‘F£¯¾z,„èõ
+Â(¬J°#‚¾qÅ2”ߍPÐZÓN¡dC†àE¼ÏN—Ú‘hG½i¬ÅÁ¡Ê8kÝÿÏ؛5Iš×bîáñ­¹UUVU¯Óݳ÷`°ò‚Øš—0#ïå¥ìJfzÓ/қL¿B÷‰&M&Ҍ¤¡ b#H3ƒž­÷Ú+³rÏo‹Åõ™ÙÕË@ȗήÊÊíóˆp?~üÓ4µ"²e™& 8¨J3›MSMGê\Äi’K']¡$j”Âc$c…Jy¯5€BÐÀš½VÌYƒ7]©$‰)
+$jҊ”bÔ¨b]4ÕÅdì<
+'±$µ·»ÛÎÚy’½qýÆN?kw⬤ 4>蘡Œ´Ž’4k·;;Y¾•·{i֊ãT)-•"ÁŒì7üBÀ!è)8O²'DdOBcÚ¾\.<x°³³³e/˲€/´Z­ÙlÆ̳éÜZc­Cä÷ßïììl4i¥˜]]•$€m¼óBÈu]°Ò{"ŠStÆ ¦Ùdæcyûí7¯ß¸>™NËÅroïãßüV(©çcw¯[ˆBgZ
+AMQ(ÁˆEY•e§iÞjÅY§±’Qdy¾³ÓßÙÞÉ;E€Ä ˆ(µŽâ˜??ÀĊ|h¨b—¾x ×¢.›Q>^³þ™™Ë² bÝççg'''­V+ f-—ËÉx2 š¦F„$ïÝûQžç?AŠË«ì'@äx)©y^s­ûE¡ê†y½¼qýúµ+ךªœŸ{猵Ãá nš­í­k7®9v,ØÔ&¢8Š"‚mˆ—áù7<OD,ÊéááµÛ=)u0Ñ "€qÞpâ‡äD¬§6©ÛK›Ðº¬yᇈâÑÓ§ÃWKj­ó¼–ŒÖZoooK)›Ê„‹b<çY^–Å¢6uª„"Lk1úœ@*°@D‚Ù*%„@Ff`@Rº1 9ύ© kçY«éx¼œ5¶‰’„ˆúý}%µÒ:Šc’RhM¤™Ù1[kéE{ßðïånæ*©ZC/Ÿa`ß³qÛ"†Áù(Šž<yÂ0‚¨,Ë@auÞi­›¦fï}Y–×®]ë÷ûG‡'!ßßÀô—£êrx…Ã1ԛj.¾ü싷oÝyëÍ7›²Z.—ùWÿy¶œœž\¿vm1Ÿÿýßÿnݹùf÷k½V«.õªõôâ¼rˆ’+û×>½ÿðàøêþqÔò`šº(Ë*|Ò\©ðn/§›—Ãèµož_°Aç<¿Bˆ•Zë¦1eU„¿ét:wïލ¢¨XÌа/' uÔꖍ]«cM€Â³ ðƒÁ !œ2¡ÃC„ž¤´:‚W<eF®MÝX' J±,KcŠã¸•ÇIJR5‹¦öžÓ4ËÚ­ÁùHî'üÛ;„ðõÁ iøúÎó¥v\ØÄSøÕ%acŽ¢È{? æóy¿ß9ݸq£Óé4¦
+’ -Œ3eUFIšµZ(PH%µÞÉúµm¦Ó¹Ž"kmY•qœÌfÓ,oÅR!" B©ü+ÌÕW>üóóoÇðZC¬ØC¶1 6³Ú!òâ8€ù‚˲ â“ÉäììŒH²ó¡Ü‹¢¨ªêápøλïüö·=~ü8ÔVAQü’©Åk¢Ê¯E¿š¦Q€çǧ?ùçŸt{½üð‡ó²˜/—Wö÷Ó4œΆç{»»»»»ôŒ+¬‚íà«×Hè[·Þi·ZA~â8Ö*‚6Õæ¯6ߛxΈ|
+Ò¥Gnv,¿úz9°Â²ËÑÑh­Ó8®›
+#5˜Œ"¥¯î좊/“^¤z ‡„Ö;„•@àCT NtLöd Œdh¼w!ª’<„¢,1É2éÆZ©¤T
+M$0’’V‡ @I¤”")IøðfIRI2c÷>ÒQœ&Ö¹ù|Á€­N‡¤ÒQ§)
+¡”TJi-·[!ÈZ×ÞÚ)ª&J’«W¯7Æ5uëtx~ñåƒÛÛ;KÓévË¢
+„ûÒ#¥ ¾FÔQá݈°+rÇíVËTMSUeYnïïöw:fx|aÝV»M€‰ç…gƍA¬TˆÅjv"0ä=" ¥¤RÖ»Ê4Rë4ː(H
+Hdœ›Lfq’Ø¢˜†ú+Š" êt:Q ”qœÑ|¶Ÿõ¶['§Ï–‹Åo¼q>8MΈèË/ëÉdzûÎíùÜ<<9å¼ÕuÖÞýà.IŽbr\×M´µÝï÷§ÎƒÒqšµ¤Òa º,ËóósfnµZMÓ”›
+.\ŒÍze檪ÏNÏî~p÷÷ŸÜuÒjµF£QÇA¿$8¾„­…Ú6eA¸NA†yooo2N¦ShšæÙ³g¿úÕ¯®\ݾ~ý&3?xðeY.Ð+ԆU±2žxM'ƒœÉK¨Ç+IÒ^›8B„RFk-„r΅N× %IJ’yžWM-˜„$@l¬)‹"Š’kW¯îïí!Ãxx1ê²Üí_Wó£áY73I¤5{bdÈ^¬b ‰ƒw¢`(ˆ¤TŠêÆxæ(Ž¤RÆ;DÁ€JÅÖ»‹Ñ°¬ë7ºÝÁàâìtÐëmµZí^o ‘”R’¤÷ µ"’]½ºEÑx<ÎóÔØæ“O>RJcŸ<%"fÇì:Ý6
+žyùöÚÀzé”|)È.׆dlø4­ˆ˜¦óÙüåÀJ³”Áz˜Í2ªª’$‹ãX)©¢(ªëÚŸ&(8‰Æ^<Û»Ûä­˜mp‡†ÕF!ž‚éÊ
+¢ˆ³IXö(€ÆƘñlÊq’Eqõêõ³ÓsDlšˆ•ÒeY,E’äR*I:ɶà ,ø*Ún'×k­Vª1Ƴ,
+ÀXÓÔUc ‘dö‚ˆ=›¦fï€^– ‘YžÂ XÍç¡öÖ)A$u{«MDóù¼µ·7™L–Å’ÑÖÃó¬Ìúýþ¬¿›àUÍ{1ÄX_“O¬W£XJ@d!; (4€%•T
+χO>iå©^Á ¾ª*ôk3öð¡ÄZþ«ÚÌ/=k 6SUËÆTZÇY¡`çŒ@’l ˜W÷VžIÏhš†½WR¦IR23Ãv¿ÿÞ{ï%IR–%"~öÙg?ªª*Š¢ù|6ÃÅbñû£©¸±ÝdìDô¾ŽbM©†Ð‘`$A(X IH„bÕáwkòÉdz¢gƒQ¿ßÏóüÁ—‚Ÿ@˜33ÆÌçsiçÜh4*Šei›ºÉ³ö•+W­ud­ýÕ/1L¬µíNg±X|ï{ßët»Œ&H`8~òÉ'[öÅÅðg?û—ÿú_·³¬}y móÕommÝ»wo:~üÑGÃÁè­·ÞLÇãÉ
+EŒãxgg§×ëåyž¦ét:ýéOúçþçwîÜyðàz/¥tÞj­ú»;çççh!L;^.þy=P~¸IÌ«eQGÑñёwV*ñáw;½®Dyy»úª]góۗp9¿*(/…,„ão>ŸWUE:Žb)•sA”$„óž_•leYš$iKP‘Œu”D±>jÐU_K¬4þ˲‡Î¹V«õtQ|z>^p$TŒˆ,$Æ
+D2ôº®“$¹wïޕ+Wž={öÑG-—…”j±\ºµ_WÈG‰¥”³Ùììììììloo/p†Ó4vÎJ)nÝz£ßßöޅÑÊË\Íp1xöB-i]µ,烣££g‡Ór¡’À%üJùڗëuÈü xí“lž<‹EQÎ{)•R{®dÂå¥?I]b¥I¦Q\é̔¤ZÚé|þ›ßü&„W8¤T¼aºRvóöÁà4.£ýíLÑԊ½—N‰” aA0
+B°1¤P²1søì÷þìÏþõWÿöÙgŸ[ë"Òº“}¢Üßßû«¿ú«,Ë>ûì³û÷ïÿèG?zÿý÷ÏÎO÷¯ì;g¼÷7n\cupð”P¬‡2üæBPû…¨&@SÖK1·Ö4®Ù¹ÒßÞÚMQÁ¥ó—uFüå`
+·?œfʨs«F{{£(bFc]h©xÌV)ùªvƒH’$Ž¢8Žó,Ëó<I’HG±Öq‡­bCÙafæ xÊDΣñx,³í…Ì~{<üh8žÕ…fhJ_-]]²³ À‚#2 DÁÅt“$I²µµ<m•ÒívK)ÅuUœœx者 Ëz_IBŠP(©´ÔR{'عD«÷Þ~{:{k‘9]·Ý¹uóùlº·×ÿñÿãÑñáÇd­‘’<¯Ì™$ŒÖuÝjµÞÿý÷Þ{¯Óé ¢Rz³g„¯(Š¢n·{íÚµo~ó›wîÜ©ªj0|ÿûßëí·²<MÒ¸(—$Å·¿ó­7¯Gq¤µÞWx=‘¶A%V¨&ËÞ;kåòøôä|<b~úká«Ë»Î姅y›=éeX3a¤¬ßïommEQ̘‘HPXø:-]‘¥i;oµò<MÓ,M[yž& 9g‰(MÓ@ª Š±º
+ïÀ,—˃ãsˆ[&ï~1š|1V
+,yôÆ5U]MS¯òD!<{&2ˆ‚-­lÐ]·ÛmµZyž÷ûý4M˲ªëºÓi‡þ4Í‹óóó8NP`pÜßß÷k ¼sÁ«]
+¡ˆœ1ðî;ïÔeÉÞ# ”Ò+‰Ò$¹}ë¶Öúððàk_û`k«û/?ûé“'‚ÚEþ¼zJÓt¹\âÊA(%é¾Pç\UUÌ<™Lþîïþîÿñ1J©?þøË/¿¼zõê›o¾ùÖ[o„}ÿúõëaѾX/]éÖR[W%0’ãñøôüÜ]¢©ü3ñrw9€þp!ì¦B¥$‘§–µ.D•Ö‘Ò;BH©Øó«žÐ¢•¦Vžgi’D­VîıneٕþîÖVk«¿½Ýëv»ÝÎN¿ßív%
+°N I…©§ƒ¡³.ï÷Ë(ùôdüð¼Z¸¶@pԔ¢œaS2³ô¸ž†&Q”b¤€¬wŽ™”²tœf­¢œL¦UÕt:="å¬GÀù|TV³4ÕsÞÞÞi·ºÎ9ï€'Bï÷Öy[›ÊxcÙÔ¦Ú»²»,‹bnlÝ4ucë€ØÞéçyûÑÃǒÔûïÝ=;=ýò‹/¼3›ä=4ÚVô@ˆÂ{^.—Ãá`±˜Ï“ÆԌ’G½˜}ôÉ£GŽg³Ùb±øå/ùåœåïï‡ßþ֟(ŠØ¡ºÝîQžçᐢµóå&6[‘
+i¨©d˜&ƒ“Së,‡ØwÁÖõ«iBð"ñ^F]ß,sx$8ç½wD’H[ƒ¦¡ºÄÉxY×Á³¼7ˆ^FBTôª+¸Ì¢ˆ+ë:KöÎ:g”$o½·\T•SÒZëØk­{!„bäÆxÀª®¡®«ùd,VIV4öÑÈ To_Rp 8aJ»œ9R”¤‚Ø pÞyd¯™H €(Œsž!ŽR¥!¤Vº×íµZm!p2æ­HiEºªªÝþž÷`$P98À$ %‘$!¥q6måãéäéÁ³v·ç¼W*vì­ç¼ÕÙÛ½òøñ—'ǧÜýàÑÃGŸ}öé»ï¾sûöÛ¼¶ˆ6Æ\\\‘Jâ̵øæ͛ˆ8›Í˜½RÒû•oă¿øüÁÿûßÿy4…>®I)ŸÞÿìèðäÞ½{oܸýÎÛï¥IΊ4M«ªJ’$l?â/8f¶Îo­wZkg,“$FëœTj%/ÐlzÎYØs—됿šõ‡‡‘D"Á±Î…Q,X¹˜0(©e±¬ƒažÇûû¢`vHèÙ[×"i/V–9æ$€¢k§ç\UÖuÕX`>Ì# [U¦©3vYW¦ª”5†Ër8´­N¶½Õ]Õ¯ž@Ò{c»+¤©¨.¢97…yS¢lã¼%Y"RXUyž+µ<jµZÌahØ)%«ª:99‹£´,«(Ò¦qÝnÏÛ4͆_+Ċ«ÈžPI€ì¹ªêÃÃÃ?üFȗÂkµZï½÷Þ§Ÿ~|ppðýïÿÏþìÏþæoþæç?ÿùNÿ
+¼þêÅ~ýO˜›¦év{i3{"
+žiw»4͊etýZÚjušÚ#BHݚƒˆ¦iì«ì%¥÷>‘£¨AÄv[, f_šZ”¤‘ã”4Íçށµà.ŠÉ¢X
+ãg‰‚•’¬k’4ÎsM`PãV¯§¢þà´þݳ¦b÷A©Š¬kj¬&p65ót¯Fíd¹G žµX±SÐ9Ȉž™{[[Bc¬s†£ñd:Û»òV§»]WµTêøøäþýûúÝ?ýðÃCîrpppÿþýo}ë[W®\D<|òäé½{÷Ò$6¦Ñ$÷vv­µÎº$I˜YéhÿJ ‘
+D"%%×U(„ŠtÖÊÓ<GãÉx:#²g„Ûo½wý·vQÌ˲`öe5“´:i2ŠÊj!8ãWƒëº~øða°ä¬ªj#”â8ÀiÎ9&,êJÆ*înõ®Ý¼$9k­@Ð2*KÛ4ŽµQZíV»i¬$éü>xŽ£nK: î|p®‚Þ)f?™ŒóE'y«+I6Æ9ïÉpX‡ìƒì»@ÏÞ5 ¤æúj²$É
+Ò8êVÈ ÎykBfMQ,­3 PÖÒ9S¥"RIã­sN¡dYJc­|˜HÂjÆŠºð#×Î[ý«7ËÅò‹'ÃJ-o߸²ÓÉ0× i7ܔ†ŠN´»—uw ”¯-£RJ%Á{¶×¶š/A!Hk(Þ~û$I¬õ‚¤”*I’,Ëx±XÄq콪“ɤÛí¥*ÚêmUei­”D„Všóëß0Æ䝶6ֆ)¥4Óc%ÉV«ôæ‹ùl6;???=;›Œ'ì\½t¬Þ}ÿîöÎ~]Þ6Ëb9NÙ±Sš½óÆy'XXð€ P`S7ƒÁ `ÂËuç1D@ØÂ6™D±Ž5 Dqűuîðè¨Ì;ý~_JÕË ÖzÖ¸j±(’4õÞecç™ùá«`f#„0MžÝxrqzz²ÕÛ1n6›9k[íN’¤UÕ9ĕÁCPf!„ó.”VZkg¹,ªW›Ð+ùT†$¤`´¶¡:²¦1‚H’,”òαçM­€‰8ŽGËÂXk­ÓR.,T¦Iâx¾XÌg³þN?Ï҅m¾Çίo·nö;½¸ã\%L%še±<ŽâN¿ÓÛïtv(îºÕð…"R¡Ani‘dd{{[ª>ÂÌý~?xÇÛ&´â«N§sïÞ=(˂Hîïïïîînr¸¢(¥Rq–:`c¬Ä´–5 ݅F„цû÷ïþùçÇÇÇË刈„<o½ûNç¬*=‚qn¾\VuI˦®MíH‘·>8œ
+±WËb9¼8žNg{{WHHcÄÕ Xy̬X_ˆÇQ¨“f³ùd<îtÚ»»»‚èâ⢮ë~¿Ÿ$IÓØÍÐDx3aç z»P–eQ̼˜“éäU„V*¥P¬Ô¸ÃŠ ORVÖ6u½Þ<)”!:Šqó½7MÇ1˜¦ qŠ!=òÂ8W™º\ιý½ý¤Ó£´3¾,.–ÅÕN²·•o©HÕUäëeuîÌl±ÈIw?Ê»qšGi†$õ>V¤@1³$HA¬6d­u»ÝŽãèh8F½^/À•»»»D²,Ë8ŽÃ’X©ŸjY諸öÀ$€„aô>à ƒÁàäää÷÷?~öìÙÁÁÁl6 lOӘG˜C†D$¼CfDË岪 çŒ Ñêæžíb²`tŽQ€°µ‰âx±XœœœÜ¸qãêÕ«aß
+&.¥dDç\’%ýÝ~p–ÜÝÛS¬«¦Ñ*ÎÛ=f6Ɲýþ÷¿wŽ¿ño§IìÍÄڒfÓ¡
+ÒWÞùƚf¹lêZJR.Ë¢¶NeVϕÉÑàøxxqcÙ³Ÿí¨˜˜ yh–óårîƒ(iõvö:;ûI«‡*AM픒a»
+‡Ã^o+ÀE¼žÁ""@€‚= Œ’¸¬ëÅb1¿/F'''ÇÇÇGGGMÓX·ò ì4ˆtdØxvž½µn4yï‰Ú4EYÖuˆÎûªq΁ŠTœF2’Ö:Î[šaq£Ã`7 ¡­¤"É5‡…°aŒ.†¦®´Žœõvw{»åÊÕN+ïv»ÏžZkIX\É¢ãŽßœEEQ´Ú­ÙlòÑGýâ?^œ3sÒÞyóÎ’r6Î‹ñhT•¥­Íx<¾¸¸˜N§
+8¶¥ð ›mO¬guVÇ«wDôO蕆©µ~í„J(¬s(ê,K=
+R¨BӜp °qÉXƒÚK%Ó<3Aˆh¨ê’P`–„ˆ¥r ‚k°ìàb4@Iy»‰H¶ZE]|r1?m\¿×jçI u¤<HƪĦ¶°Ö\ N&O¿x’¤QÚj÷ú[;»y»w¶‰„RZk¥µV(¼qZë›7o6Móµ¯}íʕ+{{{iž¦ŽŒ1MSc˪,Šr¹,çƒÃ£Ã³³³‹‹‹ÅrIì|¨pQŽ›Ö‘ -]í4É$Ž­1uݔeÈ)É;_•UY–­V¯cL§ê4aÁŽXÅ©ŠbŠ£vUÔÃӉášY"¬.Ø|ºÌòƒµ› 5npv‘¥™±æŸþï~üæ³o~û[·nÝi·ÛíNg<>yz’µ{Ýíñ|抲h·Ú¥W¾âHGyž¼¨§¦ôsøÙÏ~ñӟþôÑ£g¡y`Œg(?ûøþMA=†ˆÂx;3³c€k®£¤Ê4¯:Ø=7s „$
+¥£V*Ž"ï= ‰Š cm]×À¬¥,ËR
+KŠ¼÷l½"åÁ¯mŸâ/¡—›t¬±UUyïëªþÝï>ú×û÷^¯wãƍþð‡{{{eYi-«ºžÍç_~ùežçƒÁ`±X GD±³³³½½MDEQEñùïF#cÌz—ι•A†/n¢ֈ¾¼¶§|ñÆpÖ~XáŸçGææ¿W/%VT]Bi]Uu¥t¤õBiÂh½Ílk£V2Î
+I)bàsRÇRp¾1&°äŒ1X×ÞÕ¶¶I¬w{´Õ2ŠØÙژ²¶¾¬ª8ÒJx#00dô–gŒ¢ªÝræΟwк•Ÿ{Àˆ›¦qìA®L÷6Œ^ç6*°&”öÞ3
+ˆ¤’(QRfÝ.!5u-Ù²oŒu«$Á#¢iÌx<N’”¹1ƚš‡çãó³Ñx4õ$©•wˆeÅÕ¢6MõU6¸¯\29®÷¾®ëUœ$ççÃáùÙYw7˲½ÝÅröìÙ³‹áŸž]\\xÀ$Iƒh÷~¹\4Mcµiš@ÖÝäõ_Ù¼&¾Ú,ºü0±RÎ}%°6ºÙœŸÇì%,DiT*AVGœ7²)=7í: óe)%¶³|UÚHł²4Ýîvcóóù<”Wá=I)ÙÛÉdIàÓ$Q:ӊ< u¼\ÎG£ ·\(IÈ~+d'eðŒ‡(ÐðŽïE8þ1ø›·Ö+;­_K„v)â†ô›8(3si")¥l·[JiÅeQ,–E]TÀZ&© ®ÃözˆÖZ%ÅéÉÁ¯ýë³Ó³ápXVe]׎Pô:ÍÞÎ^+ÍMe—~a_±æþªÐ
+hnY–•ßñÞ¹))°Þy/Zí²©‘YÄ12ÄJ! w^K ˆ>h;)E‘`´uÍΕU½¨ê8ŽRE2BŠ­¯ÊÂyç­.w6֘¥
+™¼ó$H±Þyr.°a‡RÈx0èM*ã½Çà‡à}€å²,#¢$˴֝N7äÎDTUÕp8*Šbx1vÆ&Q$¤Š$•B@.Šb413€_œ>yøèìtä,£`$5֍‡Wy­µ©jo›K)ʺ…~ó梀”IÓ4¦nÒ4a†¦¬lӏï<H!…1f>›Ycˆ(Œ7·ãuCúÛ7a´ †Ë—´Þ¤@×ø×ô
+Ba­‘(„óUUY¥Qpž‘Â$mU c#­Ë¢ðÞGq$¼ÔQ„γ1iI¥¢$Ëò–u—EY–K¤ 0KŽeYT}M䛪©kBôÖxc™YH)‰4¡7›EÒ,ã,H
+xúÇ
+*#!þÚíööövEY«€RªÉtrqq¾X.†ƒÁ¢® išXGQ;ç¼µ:Š–å2´"ö÷÷÷ööêjî\mšÒ$-˅÷ŽHˆ¬oóe¬8ÿh—MŸ`s*%I|óÆͪªŽÃ" ‡¸¶Æ€–S”õ`±Ö;G(@€àÕ!΢_Þ¢^>µ^Ô[{9°.EÞWÖåØ
+#äÂ{@ç°t$@h©5ɊÊH*%=ÆP9#"³ŸÏæƚ¤MF“¦iØ9‰B VP1sÀúk|Uc")“$öž¥RÛÛÛW®]wÞ[S?yúøøpà­SRDŠZ­¨LfQ–DÝ<×ÔÅØ/–‹Æ®*g-1I Š"ˆÆÏ,µ@É%Q’¤Q¤QI¥£HG10kò,ït;RÊÆòl>/Šâôôô|0@€ÅbR
+
+²m¬•R–uåVUå›)-•j·ÚQ¤…”äIÖ͝ÍæÅÂøᢐRÚ:ð^œcX֕Š"™gf¾D’H*¦m“8BoíhÄ—Óòû_ÿ÷ÿóöÿÕnåÓñÅáё5FªQèq¡Ò–R%‰@ PJ
+ĺnš¦A„«³{uˆ3WÍjxy}’0OÆ#@Ɓ¸¢0{ör8灐”fk]@øœ³èXJU75H¥B)¬©PÂ?—@F
+QUÕIš\½vSFéùÅÐcœ%%‘Hz¶ŽµzÕú«o4Œ×sþzmmÐá0OY’åyU׍1Y™fij¬5Î6MSEUU€˜Ä±âyí¢4qö‚A‰bi4M3™LœsuUm:Ù~m=åœ 
+y–ˆH!Ô]»¼¾ÚívÆØ¡?pa´šµò¨P$ƒrNµ«Úº‘Œgyy9ŸÍbŠ÷«»»»»qô ýg­¹¾º–“ìg‰Ê~¿ËP´ÒTˆ 7M³¼\6uS2ňÊz½îûƒTõg³®ëf2‡ˆ1¦ín›(mX`ûWWWõ Ã0®×ë£uN8Ê{úróùüâ₨h­›®#€D9 ÃJ&Òå ù ÞÅPqž\ðĔ"Ÿ];ídЌƒÒ@%¥„ÄÊ13C¦TQI9£RUUÍf3—+΄Ä\
+2+PxÊ%ōªª$‰ Á¸
+(Oê:ÌÜ÷½t-÷û}]×uUMÃX55 R¦c{ ‘ªªŠ9'"böÞOý4 ƒÌ#œ܄pr,W×ͦXŠ3FI›åxÑK©g]f”•RŽ éÊ# ²ÆkÎë梛IÂþôéÓår9cÊe?ŽÈHäàb­»¼z
+BJÆû0R¦ ¼¯›¦3ÆDeÏ… +]sá\˜Q+¥
+£.…–Ý•Úl6©PŠ¡h½ÐîŸ綇ýÝúÁ¶­­ªfÞÝÜ|”BØn·Ò¡»¾X.‹£Ü?fnÛVŸ‡¾'FTà*ÿ鳏=èïøa7¨•º¹~2kÛû»7Ê(ëk¥Ô‹§c¶Ûía˜èáAkýüù󋋋iš¾ýöÛRÊ.MŨ/^è¯n_M%çR../¿øòK­µ sêº*‰ÆðüÙ³ùâŸV«×www~õ6êÉÅå—Ï?Ý.®¶¿Y¯rÿõ‹/ç‹Åý›{Q:ô‡Ënþù?~q?«›®mÿûOB­r)‚€ª®û¾1
+ÜÃðõW_SÌF)kl.™™ʲÝneúcš¦ï¾û.¥ôìÙ³ív»Z­J)¯^½úÃþð鳏}割ô¤^¿~-Û^¥Tß÷›í«×·ýÐÿp·z¹º­«úööUÈIkóÇ?þñõ7ñuÕ\]´WKx½Zݾ¾˜aŒQiý§?ÿy½Ýl¶iÈ‘V:Œ“RX
+·^Ì}ÝXoí./ÚùL
+rU¼ê͛7Ûýî0MÓÈb]×1FÑѵ ¬R™¨j››ŸÀ¶n¬µ’•Ê…ýËW_'§CPÖk•V›ûuå=†º®C¨5)@€«åòæê ­aß÷«Õj°ÖŽãH)×]»¸Z~ûÿù¶{üâ¥ðG—<wàXG=ï•RF*C†Žƒ1¥CDÎ眫|•)g¢”SŠ)ÆS$¢B4¥OØꔒ€ÁÀLnR¡ifF›aШ(§’õN…ˆ™Â0…çÕjµÛí8¦œó8M„l¬ÅRåÝ.hÀÊúeݶ—M¿?l»Ýn7M“¨âh­×»í0 ÖZ`î‡A)å¬UZPÚZÅÇ2Û4G²Ö’€yÖ´Z©õ›ûa”VZë3Û¢TAe{;HKÞûv6‹Z&ºó>D"z8쪶É!úª’N³÷>çlµ¹š/q"NTòr `”Fk•5…Ëv»Ýí÷gš‚3P½”R×ÍÜ»ãaè§CŒuÛ8k«ª’8}\ˆ
+å°~X§)¤˜€9B­ëº¾¾¾†ÓÜpèA¸I~½c£ÔÛk¢B<÷**BRJ1þƌÖY"2†‰È[9],¥HWV¨išäd.S ò»Ä0D¬]<”ù÷âQ+]{g¤õA…]H˜©Ô±mZ]²1všÂhFç}Û¶¬° „‘²[R6…=êÖxßÀö°2µ˜ó8 *•âÍ1„ååeݶZ©Z[Ò¸î÷! Š™¤! âŒ‘^…¸Žd$²#M‡s Aî(ÔVDVY˜¦)ä”Æi¶XH K:V,%§}œÆép8(4Úsˆ¡EÊpÿð •jÚÆûª®«®ëè0çbJó‹Å~ÞÜ¿¡L
+‘Ë‘–)Řb4Î)£´R…Š¬0ÀÌuÛ
+94žFjS‘Hh›~½c+üæëˆå@ÐJ1¢bf.(<M¥¨B\ ‘¡BÎY*”sN9KF坕ðNÀ>º˜"paÁ—‚½Råe¡L¹NH…Èji PI)7uÙƒÖz®pÑ4C×µm{œ©¢Ni§´Rj*ã°?|óÕב g£
+S!N¢a]röÆ**Üøª2 …)E&1C"ßTÄSÌ\œsZÙB¡l¼uóNJe璲TéÚ¶µÖî÷{YY8$Ð &*!gm5tÝl¹XXk°PÑFk……¡nëë©öŒz¦Â¬0§$i“ÕÚûŠ*ïçó¹HH ¢F…ÐJ)µ¼X pLéaQÄZ °2† ‘$¢ ±
+\«RÊéŠrÎ1ÊßJEÞra§ôl6«}Å̍¯¦iJ1©\lAgÌ0M l”BYF
+¾´Þåß6M³X,d+pÞT‰KåœÊ{[À_¿+üö“ŸõWoòQððôãÇßO«í{/ßyó=Ǒr†SŸà§¿¯èŶó„F:?#ü6¨ò<©‚ïLœ‘DAðxBP1%«Þ~‰ˆò›<RçKq<IÄ÷iòÎ-ç|úD\|.¾G‹…€|¢P8^)|粋Àýû__Îô!~‹s›OW p91L^-—ïœãÿ¥c=ÚÿûÛ2=öh¿ÒëÑ>ˆ=:Ö£}{t¬Gû öèXöAìѱíƒØ£c=Ú±GÇz´bŽõhÄëÑ>ˆý/”Au•ËF¶•IEND®B`‚
\ No newline at end of file
/advdemos/branches/advdemos/mesaref/mesaref.c
0,0 → 1,516
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
*
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include <drivers/glib.h>
#include <drivers/keyb.h>
 
#include <GL/osmesa.h>
#include <GL/glut.h>
#include <png.h>
 
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <kernel/log.h>
#include <kernel/kern.h>
 
#include <stdio.h>
 
#ifndef M_PI
#define M_PI 3.14159265
#endif
 
#define WIDTH 640
#define HEIGHT 480
#define BYTES_PP 2 //BytesPerPixel
 
#define DEG2RAD (3.14159/180.0)
 
static GLint ImgWidth = 0, ImgHeight = 0;
static GLenum ImgFormat = 0;
static GLubyte *Image = NULL;
 
#define MAX_OBJECTS 2
static GLint table_list;
static GLint objects_list[MAX_OBJECTS];
 
static GLfloat xrot, yrot;
static GLfloat spin;
 
OSMesaContext ctx;
 
unsigned char *rgb_565_buf = NULL; //RGB 16 bpp Buffer
unsigned char *video_buf = NULL; //Video Buffer
 
unsigned long int VMEMLONG = WIDTH * HEIGHT * BYTES_PP / 4; // Used by copy_videomem_16to16
unsigned long int RGB565MEM = WIDTH * HEIGHT * BYTES_PP; // Total video mem
 
unsigned long int PERIOD_REFRESH = 150000;
unsigned long int PERIOD_DISEGNA = 150000;
 
unsigned long int WCET_REFRESH, WCET_DISEGNA;
 
TASK refesh(void);
TASK disegna(void);
 
PID refresh_PID, disegna_PID;
 
void read_png_file(char *file_name, GLubyte **buffer, GLint *width, GLint *height, png_byte *color_type)
{
 
int y;
png_byte bit_depth;
 
png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers;
 
char header[8]; // 8 is the maximum size that can be checked
 
/* open file and test for it being a png */
FILE *fp = fopen(file_name, "rb");
if (!fp) {
cprintf("[read_png_file] File %s could not be opened for reading\n", file_name);
sys_end();
}
fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8))
cprintf("[read_png_file] File %s is not recognized as a PNG file\n", file_name);
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
cprintf("[read_png_file] png_create_read_struct failed\n");
 
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
cprintf("[read_png_file] png_create_info_struct failed\n");
 
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
 
png_read_info(png_ptr, info_ptr);
 
*width = info_ptr->width;
*height = info_ptr->height;
*color_type = info_ptr->color_type;
bit_depth = info_ptr->bit_depth;
 
number_of_passes = png_set_interlace_handling(png_ptr);
cprintf("Open PNG W: %d H: %d CT: %d BD: %d\n",*width,*height,*color_type,bit_depth);
png_read_update_info(png_ptr, info_ptr);
 
row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * info_ptr->height);
for (y=0; y<info_ptr->height; y++)
row_pointers[y] = (png_byte*) malloc(info_ptr->rowbytes);
 
png_read_image(png_ptr, row_pointers);
 
if(info_ptr->color_type == PNG_COLOR_TYPE_RGB) {
*buffer = malloc(info_ptr->height * info_ptr->rowbytes);
for(y=0; y<info_ptr->height; y++)
memcpy(*buffer+y*info_ptr->rowbytes,row_pointers[y],info_ptr->rowbytes);
}
 
fclose(fp);
}
 
static void make_table( void )
{
static GLfloat table_mat[] = { 1.0, 1.0, 1.0, 0.6 };
static GLfloat gray[] = { 0.4, 0.4, 0.4, 1.0 };
 
table_list = glGenLists(1);
glNewList( table_list, GL_COMPILE );
 
/* load table's texture */
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, table_mat );
/* glMaterialfv( GL_FRONT, GL_EMISSION, gray );*/
glMaterialfv( GL_FRONT, GL_DIFFUSE, table_mat );
glMaterialfv( GL_FRONT, GL_AMBIENT, gray );
/* draw textured square for the table */
glPushMatrix();
glScalef( 4.0, 4.0, 4.0 );
glBegin( GL_POLYGON );
glNormal3f( 0.0, 1.0, 0.0 );
glTexCoord2f( 0.0, 0.0 ); glVertex3f( 1.0, 0.0, -1.0 );
glTexCoord2f( 1.0, 0.0 ); glVertex3f( 1.0, 0.0, 1.0 );
glTexCoord2f( 1.0, 1.0 ); glVertex3f( -1.0, 0.0, 1.0 );
glTexCoord2f( 0.0, 1.0 ); glVertex3f( -1.0, 0.0, -1.0 );
glEnd();
glPopMatrix();
 
glDisable( GL_TEXTURE_2D );
 
glEndList();
}
 
 
static void make_objects( void )
{
GLUquadricObj *q;
 
static GLfloat cyan[] = { 0.0, 1.0, 1.0, 1.0 };
static GLfloat green[] = { 0.2, 1.0, 0.2, 1.0 };
static GLfloat black[] = { 0.0, 0.0, 0.0, 0.0 };
 
q = gluNewQuadric();
gluQuadricDrawStyle( q, GLU_FILL );
gluQuadricNormals( q, GLU_SMOOTH );
 
objects_list[0] = glGenLists(1);
glNewList( objects_list[0], GL_COMPILE );
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, cyan );
glMaterialfv( GL_FRONT, GL_EMISSION, black );
gluCylinder( q, 0.5, 0.5, 1.0, 15, 1 );
glEndList();
 
objects_list[1] = glGenLists(1);
glNewList( objects_list[1], GL_COMPILE );
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green );
glMaterialfv( GL_FRONT, GL_EMISSION, black );
gluCylinder( q, 1.5, 0.0, 2.5, 15, 1 );
glEndList();
}
 
static void gl_init( void )
{
png_byte img_color;
 
GLfloat yAspect = 2.5;
GLfloat xAspect = yAspect * (float) WIDTH / (float) HEIGHT;
 
//Create the OSMesa Context
ctx = OSMesaCreateContext(OSMESA_RGB_565, NULL);
 
//Make Current Context
OSMesaMakeCurrent(ctx, rgb_565_buf, GL_UNSIGNED_SHORT_5_6_5, WIDTH, HEIGHT);
 
read_png_file("test.png",&Image,&ImgWidth,&ImgHeight,&img_color);
if (img_color == PNG_COLOR_TYPE_RGB && Image != NULL)
ImgFormat = GL_RGB;
else {
cprintf("Texture Load Falied !!\n");
sys_end();
}
make_table();
make_objects();
 
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, ImgWidth, ImgHeight,
ImgFormat, GL_UNSIGNED_BYTE, Image);
 
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
 
xrot = 30.0;
yrot = 50.0;
spin = 0.0;
 
glShadeModel( GL_FLAT );
glEnable( GL_LIGHT0 );
glEnable( GL_LIGHTING );
 
glClearColor( 0.5, 0.5, 0.9, 0.0 );
 
glEnable( GL_NORMALIZE );
 
glViewport(0, 0, WIDTH, HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum( -xAspect, xAspect, yAspect, -yAspect, 10.0, 30.0 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
 
}
 
static void draw_objects( GLfloat eyex, GLfloat eyey, GLfloat eyez )
{
(void) eyex;
(void) eyey;
(void) eyez;
#ifndef USE_ZBUFFER
if (eyex<0.5) {
#endif
glPushMatrix();
glTranslatef( 1.0, 1.5, 0.0 );
glRotatef( spin, 1.0, 0.5, 0.0 );
glRotatef( 0.5*spin, 0.0, 0.5, 1.0 );
glCallList( objects_list[0] );
glPopMatrix();
glPushMatrix();
glTranslatef( -1.0, 0.85+3.0*fabs( cos(0.01*spin) ), 0.0 );
glRotatef( 0.5*spin, 0.0, 0.5, 1.0 );
glRotatef( spin, 1.0, 0.5, 0.0 );
glScalef( 0.5, 0.5, 0.5 );
glCallList( objects_list[1] );
glPopMatrix();
#ifndef USE_ZBUFFER
}
else {
glPushMatrix();
glTranslatef( -1.0, 0.85+3.0*fabs( cos(0.01*spin) ), 0.0 );
glRotatef( 0.5*spin, 0.0, 0.5, 1.0 );
glRotatef( spin, 1.0, 0.5, 0.0 );
glScalef( 0.5, 0.5, 0.5 );
glCallList( objects_list[1] );
glPopMatrix();
 
glPushMatrix();
glTranslatef( 1.0, 1.5, 0.0 );
glRotatef( spin, 1.0, 0.5, 0.0 );
glRotatef( 0.5*spin, 0.0, 0.5, 1.0 );
glCallList( objects_list[0] );
glPopMatrix();
}
#endif
 
}
 
static void draw_table( void )
{
glCallList( table_list );
}
 
static void draw( void )
{
static GLfloat light_pos[] = { 0.0, 20.0, 0.0, 1.0 };
GLfloat dist = 20.0;
GLfloat eyex, eyey, eyez;
 
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
 
 
eyex = dist * cos(yrot*DEG2RAD) * cos(xrot*DEG2RAD);
eyez = dist * sin(yrot*DEG2RAD) * cos(xrot*DEG2RAD);
eyey = dist * sin(xrot*DEG2RAD);
 
/* view from top */
glPushMatrix();
gluLookAt( eyex, eyey, eyez, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 );
 
glLightfv( GL_LIGHT0, GL_POSITION, light_pos );
/* draw table into stencil planes */
glDisable( GL_DEPTH_TEST );
glEnable( GL_STENCIL_TEST );
glStencilFunc( GL_ALWAYS, 1, 0xffffffff );
glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
glColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE );
draw_table();
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
 
glEnable( GL_DEPTH_TEST );
 
/* render view from below (reflected viewport) */
/* only draw where stencil==1 */
if (eyey>0.0) {
glPushMatrix();
glStencilFunc( GL_EQUAL, 1, 0xffffffff ); /* draw if ==1 */
glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
glScalef( 1.0, -1.0, 1.0 );
 
/* Reposition light in reflected space. */
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
 
draw_objects(eyex, eyey, eyez);
glPopMatrix();
 
/* Restore light's original unreflected position. */
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
}
 
glDisable( GL_STENCIL_TEST );
 
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
 
glEnable( GL_TEXTURE_2D );
draw_table();
glDisable( GL_TEXTURE_2D );
glDisable( GL_BLEND );
 
/* view from top */
glPushMatrix();
 
draw_objects(eyex, eyey, eyez);
 
glPopMatrix();
 
glPopMatrix();
 
glFinish();
 
}
 
static int screen()
{
 
extern DWORD flbaddr;
/* graphic card Initialization */
if (grx_init() < 1) {
sys_abort(1);
}
if (grx_open(640, 480, 16) < 0) {
cprintf("GRX Err\n");
sys_abort(1);
}
video_buf = (unsigned char *)flbaddr;
 
return 0;
}
 
void program_end(void *arg)
{
OSMesaDestroyContext(ctx);
free(rgb_565_buf);
 
grx_close();
 
sys_end();
 
}
 
void program_key_end(KEY_EVT *k)
{
 
sys_end();
 
}
 
TASK refresh(void)
{
 
while(1) {
 
memcpy(rgb_565_buf, video_buf, RGB565MEM);
task_endcycle();
 
}
 
sys_end();
 
}
 
 
TASK disegna(void)
{
 
char text[100];
TIME disegna_TIME, refresh_TIME;
while(1) {
jet_gettable(refresh_PID, &refresh_TIME, 1);
jet_gettable(disegna_PID, &disegna_TIME, 1);
 
spin += 2.0;
yrot += 3.0;
 
draw();
sprintf(text,"Hard Task Refresh PER:%6d us EX:%6d us",(int)PERIOD_REFRESH,(int)refresh_TIME);
grx_text(text,10,5,rgb16(0,0,255),0);
sprintf(text,"Hard Task Draw PER:%6d us EX:%6d us",(int)PERIOD_DISEGNA,(int)disegna_TIME);
grx_text(text,10,15,rgb16(0,0,255),0);
 
task_endcycle();
 
}
 
sys_end();
 
}
 
int main (int argc, char *argv[])
{
HARD_TASK_MODEL ht_refresh, ht_disegna;
 
sys_atrunlevel(program_end,NULL, RUNLEVEL_BEFORE_EXIT);
WCET_REFRESH =((long int) PERIOD_REFRESH * (0.2));
WCET_DISEGNA =((long int) PERIOD_DISEGNA * (0.7));
 
hard_task_default_model(ht_refresh);
hard_task_def_wcet(ht_refresh,WCET_REFRESH);
hard_task_def_mit(ht_refresh,PERIOD_REFRESH);
hard_task_def_usemath(ht_refresh);
hard_task_def_group(ht_refresh,1);
hard_task_def_ctrl_jet(ht_refresh);
 
refresh_PID = task_create("refresh", refresh, &ht_refresh, NULL);
if (refresh_PID == -1) {
sys_end();
exit(4);
}
 
hard_task_default_model(ht_disegna);
hard_task_def_mit(ht_disegna,PERIOD_DISEGNA);
hard_task_def_wcet(ht_disegna,WCET_DISEGNA);
hard_task_def_group(ht_disegna,1);
hard_task_def_ctrl_jet(ht_disegna);
hard_task_def_usemath(ht_disegna);
hard_task_def_stack(ht_disegna, 30000);
disegna_PID = task_create("disegna", disegna, &ht_disegna, NULL);
if (disegna_PID == -1) {
sys_end();
exit(4);
}
 
{
KEY_EVT k;
k.flag = ALTL_BIT;
k.scan = KEY_C;
k.ascii = 'c';
keyb_hook(k,program_key_end);
}
rgb_565_buf = malloc(RGB565MEM);
gl_init();
if (screen()) {
printk(KERN_INFO "Graphical initialization failed !!\n");
sys_end();
}
 
group_activate(1);
 
return 0;
}
/advdemos/branches/advdemos/mesaref/initfile.c
0,0 → 1,182
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
/*
* CVS : $Id: initfile.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
*
* File: $File$
* Revision: $Revision: 1.1.1.1 $
* Last update: $Date: 2004-05-24 17:54:50 $
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/rr.h"
#include "modules/cbs.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
#include "modules/pi.h"
#include "modules/pc.h"
#include "modules/srp.h"
#include "modules/npp.h"
#include "modules/nop.h"
#include "modules/nopm.h"
 
#include "fs/bdevinit.h"
#include "fs/fsinit.h"
#include "fs/bdev.h"
 
#include "drivers/keyb.h"
 
/*+ sysyem tick in us +*/
#define TICK 1000
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
dev_t root_device=-1;
dev_t temp_device=-1;
 
int __register_sub_init(void)
{
#if defined(EDFSCHED)
extern void BD_EDF_register_module(void);
BD_EDF_register_module();
#elif defined(PSCANSCHED)
extern void BD_PSCAN_register_module(void);
BD_PSCAN_register_module();
#endif
return 0;
}
 
int choose_root_callback(dev_t dev,u_int8_t fs)
{
if (fs==FS_MSDOS) return dev;
return -1;
}
 
int choose_temp_callback(__dev_t dev,__uint8_t fs)
{
static int flag=0;
if (fs==FS_MSDOS) {
if (flag) return dev;
flag=1;
}
return -1;
}
 
int __bdev_sub_init(void)
{
BDEV_PARMS bdev=BASE_BDEV;
bdev_def_showinfo(bdev,FALSE);
bdev_init(&bdev);
 
root_device=bdev_scan_devices(choose_root_callback);
if (root_device<0) {
cprintf("can't find root device to mount on /!!!\n");
sys_end();
return -1;
}
 
return 0;
 
}
 
int __fs_sub_init(void)
{
extern int libc_initialize(void);
FILESYSTEM_PARMS fs=BASE_FILESYSTEM;
filesystem_def_rootdevice(fs,root_device);
filesystem_def_fs(fs,FS_MSDOS);
filesystem_def_showinfo(fs,FALSE);
filesystem_init(&fs);
 
libc_initialize();
 
return 0;
}
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
extern int __register_sub_init(void);
 
EDF_register_level(EDF_ENABLE_ALL);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
CBS_register_level(CBS_ENABLE_ALL, 0);
dummy_register_level();
 
SEM_register_module();
 
CABS_register_module();
 
PI_register_module();
PC_register_module();
NPP_register_module();
SRP_register_module();
NOP_register_module();
NOPM_register_module();
 
__register_sub_init();
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
KEYB_PARMS keyb = BASE_KEYB;
extern int __bdev_sub_init(void);
extern int __fs_sub_init(void);
HARTPORT_init();
KEYB_init(&keyb);
 
__bdev_sub_init();
__fs_sub_init();
__call_main__(mb);
 
return (void *)0;
}
 
/advdemos/branches/advdemos/mesaref/readme.txt
0,0 → 1,52
--------------------------------------
MESA Demo (reflect)
 
by
 
Giacomo Guidi <giacomo@gandalf.sssup.it>
 
Last update 20/03/2003
--------------------------------------
 
This is a simple test demo for the MESA (5.0)
libraries, the low level graphic drivers is
the SVGA (from the SVGAlib)
 
See drivers/svga/readme for supported cards
 
You need a test.png file present in the
same directory of the demo. Remember that
the file system support only a DOS FAT16 fs.
 
The PNGlib will load this file and it
will be used as a texture.
 
--------------------------------------
 
The demo is composed by:
 
MAKEFILE The makefile used to compile the application
README.TXT This file
INITFILE.C The init file (with fs initialization)
MESAREF.C The MESA Demo
TEST.PNG The PNG texture image
 
--------------------------------------
 
- To specify your card change the line
 
#define CARD <driver name>
 
- The demo calls the grx and off-screen Mesa functions.
The resolution must be 16 bitsperpixel (64K colors) and
the graphic access mode must be linear.
 
- There are two buffers
 
The video buffer (video_buf)
The virtual buffer (rgb_565_buf)
 
copy_videomem_16to16 links these buffers
 
- If the texture load fails, sys_end() is called
 
/advdemos/branches/advdemos/mesaref/makefile
0,0 → 1,16
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS = mesaref
 
include $(BASE)/config/example.mk
 
mesaref:
make -f $(SUBMAKE) APP=mesaref INIT= OTHEROBJS="initfile.o" SHARKOPT="__OSMESA__ __PNG__ __OLDCHAR__ __GRX__"
 
/advdemos/branches/advdemos/edfact/initfile.c
0,0 → 1,99
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: initfile.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "edfact.h"
#include "modules/cbs.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDFACT_register_level(EDFACT_ENABLE_ALL);
CBS_register_level(CBS_ENABLE_ALL, 0);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
/advdemos/branches/advdemos/edfact/edfact.c
0,0 → 1,565
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: edfact.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "edfact.h"
#include <ll/stdio.h>
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
//#define edfact_printf kern_printf
#define edfact_printf printk
 
/*+ Status used in the level +*/
#define EDFACT_READY MODULE_STATUS_BASE /*+ - Ready status +*/
#define EDFACT_IDLE MODULE_STATUS_BASE+4 /*+ to wait the deadline +*/
 
/*+ flags +*/
#define EDFACT_FLAG_NORAISEEXC 2
 
/*+ the level redefinition for the Earliest Deadline First level +*/
typedef struct {
level_des l; /*+ the standard level descriptor +*/
 
TIME period[MAX_PROC]; /*+ The task periods; the deadlines are
stored in the priority field +*/
int deadline_timer[MAX_PROC];
/*+ The task deadline timers +*/
 
struct timespec deadline_timespec[MAX_PROC];
 
int dline_miss[MAX_PROC]; /*+ Deadline miss counter +*/
int wcet_miss[MAX_PROC]; /*+ Wcet miss counter +*/
 
int nact[MAX_PROC]; /*+ Wcet miss counter +*/
 
int flag[MAX_PROC];
/*+ used to manage the JOB_TASK_MODEL and the
periodicity +*/
 
IQUEUE ready; /*+ the ready queue +*/
 
int flags; /*+ the init flags... +*/
 
bandwidth_t U; /*+ the used bandwidth +*/
 
} EDFACT_level_des;
 
 
static void EDFACT_timer_deadline(void *par);
 
static void EDFACT_internal_activate(EDFACT_level_des *lev, PID p,
struct timespec *t)
{
struct timespec *temp;
 
temp = iq_query_timespec(p, &lev->ready);
 
TIMESPEC_ASSIGN(temp,t);
ADDUSEC2TIMESPEC(lev->period[p], temp);
 
TIMESPEC_ASSIGN(&lev->deadline_timespec[p],
temp);
 
/* Insert task in the correct position */
proc_table[p].status = EDFACT_READY;
iq_timespec_insert(p,&lev->ready);
 
/* needed because when there is a wcet miss I disable CONTROL_CAP */
proc_table[p].control |= CONTROL_CAP;
}
 
static void EDFACT_timer_deadline(void *par)
{
PID p = (PID) par;
EDFACT_level_des *lev;
 
lev = (EDFACT_level_des *)level_table[proc_table[p].task_level];
 
switch (proc_table[p].status) {
case EDFACT_IDLE:
edfact_printf("I%d",p);
 
EDFACT_internal_activate(lev,p, &lev->deadline_timespec[p]);
 
event_need_reschedule();
break;
 
default:
edfact_printf("D%d",p);
/* else, a deadline miss occurred!!! */
lev->dline_miss[p]++;
 
/* the task is into another state */
lev->nact[p]++;
 
/* Set the deadline timer */
ADDUSEC2TIMESPEC(lev->period[p], &lev->deadline_timespec[p]);
}
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
EDFACT_timer_deadline,
(void *)p);
 
}
 
static void EDFACT_timer_guest_deadline(void *par)
{
PID p = (PID) par;
 
edfact_printf("AAARRRGGGHHH!!!");
kern_raise(XDEADLINE_MISS,p);
}
 
 
/* The scheduler only gets the first task in the queue */
static PID EDFACT_public_scheduler(LEVEL l)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
return iq_query_first(&lev->ready);
}
 
/* The on-line guarantee is enabled only if the appropriate flag is set... */
static int EDFACT_public_guarantee(LEVEL l, bandwidth_t *freebandwidth)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
if (lev->flags & EDFACT_FAILED_GUARANTEE) {
*freebandwidth = 0;
return 0;
}
else
if (*freebandwidth >= lev->U) {
*freebandwidth -= lev->U;
return 1;
}
else
return 0;
 
}
 
static int EDFACT_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
HARD_TASK_MODEL *h;
 
if (m->pclass != HARD_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
h = (HARD_TASK_MODEL *)m;
if (!h->wcet || !h->mit || h->periodicity != PERIODIC) return -1;
/* now we know that m is a valid model */
 
lev->period[p] = h->mit;
 
lev->flag[p] = 0;
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
/* Enable wcet check */
proc_table[p].avail_time = h->wcet;
proc_table[p].wcet = h->wcet;
proc_table[p].control |= CONTROL_CAP;
 
/* update the bandwidth... */
if (lev->flags & EDFACT_ENABLE_GUARANTEE) {
bandwidth_t b;
b = (MAX_BANDWIDTH / h->mit) * h->wcet;
 
/* really update lev->U, checking an overflow... */
if (MAX_BANDWIDTH - lev->U > b)
lev->U += b;
else
/* The task can NOT be guaranteed (U>MAX_BANDWIDTH)...
in this case, we don't raise an exception... in fact, after the
EDFACT_task_create the task_create will call level_guarantee that return
-1... return -1 in EDFACT_task_create isn't correct, because:
. generally, the guarantee must be done when also the resources
are registered
. returning -1 will cause the task_create to return with an errno
ETASK_CREATE instead of ENO_GUARANTEE!!!
 
Why I use the flag??? because if the lev->U overflows, if i.e. I set
it to MAX_BANDWIDTH, I lose the correct allocated bandwidth...
*/
lev->flags |= EDFACT_FAILED_GUARANTEE;
}
 
return 0; /* OK, also if the task cannot be guaranteed... */
}
 
static void EDFACT_public_detach(LEVEL l, PID p)
{
/* the EDFACT level doesn't introduce any dinamic allocated new field.
we have only to reset the NO_GUARANTEE FIELD and decrement the allocated
bandwidth */
 
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
if (lev->flags & EDFACT_FAILED_GUARANTEE)
lev->flags &= ~EDFACT_FAILED_GUARANTEE;
else
lev->U -= (MAX_BANDWIDTH / lev->period[p]) * proc_table[p].wcet;
}
 
static void EDFACT_public_dispatch(LEVEL l, PID p, int nostop)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
/* the task state is set EXE by the scheduler()
we extract the task from the ready queue
NB: we can't assume that p is the first task in the queue!!! */
iq_extract(p, &lev->ready);
}
 
static void EDFACT_public_epilogue(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
/* check if the wcet is finished... */
if (proc_table[p].avail_time <= 0 && proc_table[p].control&CONTROL_CAP) {
/* wcet finished: disable wcet event and count wcet miss */
edfact_printf("W%d",p);
proc_table[p].control &= ~CONTROL_CAP;
lev->wcet_miss[p]++;
}
 
/* the task it returns into the ready queue... */
iq_timespec_insert(p,&lev->ready);
proc_table[p].status = EDFACT_READY;
}
 
static void EDFACT_public_activate(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
struct timespec t;
 
/* Test if we are trying to activate a non sleeping task */
/* save activation (only if needed... */
if (proc_table[p].status != SLEEP) {
/* a periodic task cannot be activated when it is already active */
kern_raise(XACTIVATION,p);
return;
}
 
kern_gettime(&t);
EDFACT_internal_activate(lev,p, &t);
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
EDFACT_timer_deadline,
(void *)p);
 
}
 
static void EDFACT_public_unblock(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
/* Insert task in the coEDFect position */
proc_table[p].status = EDFACT_READY;
iq_timespec_insert(p,&lev->ready);
}
 
static void EDFACT_public_block(LEVEL l, PID p)
{
}
 
static int EDFACT_public_message(LEVEL l, PID p, void *m)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
struct timespec t;
 
/* we reset the capacity counters... */
proc_table[p].avail_time = proc_table[p].wcet;
 
if (lev->nact[p] > 0) {
edfact_printf("E%d",p);
 
/* Pending activation: reactivate the thread!!! */
lev->nact[p]--;
 
/* see also EDFACT_timer_deadline */
kern_gettime(&t);
EDFACT_internal_activate(lev,p, &t);
 
/* check if the deadline has already expired */
if (TIMESPEC_A_LT_B(iq_query_timespec(p, &lev->ready), &schedule_time)) {
/* count the deadline miss */
lev->dline_miss[p]++;
kern_event_delete(lev->deadline_timer[p]);
}
 
}
else {
edfact_printf("e%d",p);
 
/* the task has terminated his job before it consume the wcet. All OK! */
proc_table[p].status = EDFACT_IDLE;
 
/* when the deadline timer fire, it recognize the situation and set
correctly all the stuffs (like reactivation, etc... ) */
}
 
jet_update_endcycle(); /* Update the Jet data... */
 
return 0;
}
 
static void EDFACT_public_end(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
edfact_printf("Û%d",p);
 
/* we finally put the task in the ready queue */
proc_table[p].status = FREE;
iq_insertfirst(p,&freedesc);
/* and free the allocated bandwidth */
lev->U -= (MAX_BANDWIDTH/lev->period[p]) * proc_table[p].wcet;
 
if (lev->deadline_timer[p] != -1) {
edfact_printf("²%d",p);
kern_event_delete(lev->deadline_timer[p]);
}
}
 
 
/* Guest Functions
These functions manages a JOB_TASK_MODEL, that is used to put
a guest task in the EDFACT ready queue. */
 
static void EDFACT_private_insert(LEVEL l, PID p, TASK_MODEL *m)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
JOB_TASK_MODEL *job;
 
if (m->pclass != JOB_PCLASS || (m->level != 0 && m->level != l) ) {
kern_raise(XINVALID_TASK, p);
return;
}
 
job = (JOB_TASK_MODEL *)m;
 
TIMESPEC_ASSIGN(iq_query_timespec(p, &lev->ready), &job->deadline);
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
if (job->noraiseexc)
lev->flag[p] = EDFACT_FLAG_NORAISEEXC;
else {
lev->flag[p] = 0;
lev->deadline_timer[p] = kern_event_post(iq_query_timespec(p, &lev->ready),
EDFACT_timer_guest_deadline,
(void *)p);
}
 
lev->period[p] = job->period;
 
/* Insert task in the correct position */
iq_timespec_insert(p,&lev->ready);
proc_table[p].status = EDFACT_READY;
 
/* there is no bandwidth guarantee at this level, it is performed
by the level that inserts guest tasks... */
}
 
static void EDFACT_private_dispatch(LEVEL l, PID p, int nostop)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
/* the task state is set to EXE by the scheduler()
we extract the task from the ready queue
NB: we can't assume that p is the first task in the queue!!! */
iq_extract(p, &lev->ready);
}
 
static void EDFACT_private_epilogue(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
/* the task has been preempted. it returns into the ready queue... */
iq_timespec_insert(p,&lev->ready);
proc_table[p].status = EDFACT_READY;
}
 
static void EDFACT_private_extract(LEVEL l, PID p)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
//kern_printf("EDFACT_guest_end: dline timer %d\n",lev->deadline_timer[p]);
if (proc_table[p].status == EDFACT_READY)
{
iq_extract(p, &lev->ready);
//kern_printf("(g_end rdy extr)");
}
 
/* we remove the deadline timer, because the slice is finished */
if (lev->deadline_timer[p] != NIL) {
// kern_printf("EDFACT_guest_end: dline timer %d\n",lev->deadline_timer[p]);
kern_event_delete(lev->deadline_timer[p]);
lev->deadline_timer[p] = NIL;
}
 
}
 
/* Registration functions */
 
/*+ Registration function:
int flags the init flags ... see EDFACT.h +*/
LEVEL EDFACT_register_level(int flags)
{
LEVEL l; /* the level that we register */
EDFACT_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
printk("EDFACT_register_level\n");
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(EDFACT_level_des));
 
lev = (EDFACT_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.private_insert = EDFACT_private_insert;
lev->l.private_extract = EDFACT_private_extract;
lev->l.private_dispatch = EDFACT_private_dispatch;
lev->l.private_epilogue = EDFACT_private_epilogue;
 
lev->l.public_scheduler = EDFACT_public_scheduler;
if (flags & EDFACT_ENABLE_GUARANTEE)
lev->l.public_guarantee = EDFACT_public_guarantee;
else
lev->l.public_guarantee = NULL;
lev->l.public_create = EDFACT_public_create;
lev->l.public_detach = EDFACT_public_detach;
lev->l.public_end = EDFACT_public_end;
lev->l.public_dispatch = EDFACT_public_dispatch;
lev->l.public_epilogue = EDFACT_public_epilogue;
lev->l.public_activate = EDFACT_public_activate;
lev->l.public_unblock = EDFACT_public_unblock;
lev->l.public_block = EDFACT_public_block;
lev->l.public_message = EDFACT_public_message;
 
/* fill the EDFACT descriptor part */
for(i=0; i<MAX_PROC; i++) {
lev->period[i] = 0;
lev->deadline_timer[i] = -1;
lev->flag[i] = 0;
lev->dline_miss[i] = 0;
lev->wcet_miss[i] = 0;
lev->nact[i] = 0;
}
 
iq_init(&lev->ready,&freedesc, 0);
lev->flags = flags & 0x07;
lev->U = 0;
 
return l;
}
 
bandwidth_t EDFACT_usedbandwidth(LEVEL l)
{
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
return lev->U;
}
 
int EDFACT_get_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
return lev->dline_miss[p];
}
 
int EDFACT_get_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
return lev->wcet_miss[p];
}
 
int EDFACT_get_nact(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
return lev->nact[p];
}
 
int EDFACT_reset_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
lev->dline_miss[p] = 0;
return 0;
}
 
int EDFACT_reset_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFACT_level_des *lev = (EDFACT_level_des *)(level_table[l]);
 
lev->wcet_miss[p] = 0;
return 0;
}
 
/advdemos/branches/advdemos/edfact/testact.c
0,0 → 1,245
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: testact.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
/* the demo tests EDFACT with my Celeron 366 Mhz.
Aster1 meet all wcets and all deadlines
Aster2 miss all wcets but hits all the deadlines
Aster3 blocks on a semaphore so it miss all the deadlines and it accumulates
pending activations
Aster4 does 5 states:
1: is a cycle, long enough to cope a little more than 2 periods
2-5: like aster1, they meets all the wcet and deadlines
the debug pattern is something like
WDDEEeIeIeI
W wcet violated
D deadline miss event
E endcycle with automatic reactivation due to pending activations
e normal endcycle
I normal reactivation event
 
 
*/
 
 
#include <kernel/kern.h>
#include <semaphore.h>
#include "edfact.h"
 
PID p1,p2,p3,p4;
 
sem_t sem;
 
#define ASTER_LIM 77
 
TASK aster1(void *arg)
{
int i = 10;
int y = 10+exec_shadow;
 
printf_xy(1,y,WHITE,"%d", exec_shadow);
while (i < ASTER_LIM) {
puts_xy(i,y,WHITE,"*");
task_endcycle();
 
puts_xy(i,y,WHITE," ");
i++;
}
 
return 0;
}
 
TASK aster2(void *arg)
{
int i = 10;
int y = 10+exec_shadow;
int x;
 
printf_xy(1,y,WHITE,"%d", exec_shadow);
while (i < ASTER_LIM) {
puts_xy(i,y,WHITE,"*");
for(x=0; x<1000000; x++);
task_endcycle();
 
puts_xy(i,y,WHITE," ");
i++;
}
 
return 0;
}
 
TASK aster3(void *arg)
{
int i = 10;
int y = 10+exec_shadow;
 
printf_xy(1,y,WHITE,"%d", exec_shadow);
while (i < ASTER_LIM) {
puts_xy(i,y,WHITE,"*");
sem_wait(&sem);
task_endcycle();
 
puts_xy(i,y,WHITE," ");
i++;
}
 
return 0;
}
 
TASK aster4(void *arg)
{
int i = 10;
int y = 10+exec_shadow;
int x;
int flag = 0;
 
printf_xy(1,y,WHITE,"%d", exec_shadow);
while (i < ASTER_LIM) {
puts_xy(i,y,WHITE,"*");
 
switch (flag) {
case 0:
kern_printf("!");
for(x=0; x<5000000; x++) flag=1;
break;
case 1:
flag = 2;
break;
case 2:
flag = 3;
break;
case 3:
flag = 4;
break;
case 4:
flag = 0;
break;
}
 
task_endcycle();
 
puts_xy(i,y,WHITE," ");
i++;
}
 
return 0;
}
 
 
 
TASK clock()
{
printf_xy(50,19,WHITE,"PID miss wcet nact");
while(1) {
printf_xy(50,20,WHITE,"%3d %4d %4d %4d",
p1, EDFACT_get_dline_miss(p1),
EDFACT_get_wcet_miss(p1),
EDFACT_get_nact(p1));
printf_xy(50,21,WHITE,"%3d %4d %4d %4d",
p2, EDFACT_get_dline_miss(p2),
EDFACT_get_wcet_miss(p2),
EDFACT_get_nact(p2));
printf_xy(50,22,WHITE,"%3d %4d %4d %4d",
p3, EDFACT_get_dline_miss(p3),
EDFACT_get_wcet_miss(p3),
EDFACT_get_nact(p3));
printf_xy(50,23,WHITE,"%3d %4d %4d %4d",
p4, EDFACT_get_dline_miss(p4),
EDFACT_get_wcet_miss(p4),
EDFACT_get_nact(p4));
}
}
 
int main(int argc, char **argv)
{
NRT_TASK_MODEL n;
 
HARD_TASK_MODEL m;
 
kern_printf("\nCtrl-C = end demo\n");
 
hard_task_default_model(m);
hard_task_def_mit(m,200000);
hard_task_def_group(m,1);
 
sem_init(&sem,0,0);
 
hard_task_def_wcet(m,2000);
p1 = task_create("1",aster1,&m,NULL);
if (p1 == -1) {
perror("Aster.C(main): Could not create task <aster> ...");
sys_end();
}
 
hard_task_def_wcet(m,2000);
p2 = task_create("1",aster2,&m,NULL);
if (p2 == -1) {
perror("Aster.C(main): Could not create task <aster> ...");
sys_end();
}
 
hard_task_def_wcet(m,2000);
p3 = task_create("1",aster3,&m,NULL);
if (p3 == -1) {
perror("Aster.C(main): Could not create task <aster> ...");
sys_end();
}
 
hard_task_def_mit(m,20000);
hard_task_def_wcet(m,500);
p4 = task_create("1",aster4,&m,NULL);
if (p4 == -1) {
perror("Aster.C(main): Could not create task <aster> ...");
sys_end();
}
 
group_activate(1);
 
nrt_task_default_model(n);
task_activate(task_create("Clock",clock,&n,NULL));
return 0;
}
 
/advdemos/branches/advdemos/edfact/edfact.h
0,0 → 1,152
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: edfact.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
This file contains the server EDFACT (EDF with pending activations)
 
Title:
EDFACT
 
Task Models Accepted:
HARD_TASK_MODEL - Hard Tasks (only Periodic)
wcet field and mit field must be != 0. They are used to set the wcet
and period of the tasks.
periodicity field can be only PERIODIC
drel field is ignored
Guest Models Accepted:
JOB_TASK_MODEL - a single guest task activation
Identified by an absolute deadline and a period.
period field is ignored
 
Description:
This module schedule his tasks following the classic EDF scheme.
The task guarantee is based on the factor utilization approach.
The tasks scheduled are only periodic.
All the task are put in a queue and the scheduling is based on the
deadline value.
NO GUARANTEE is performed on guest tasks. The guarantee must be performed
by the level that inserts guest tasks in the EDF level.
If a task miss a deadline a counter is incremented.
If a task exausts the wcet a counter is incremented
No ZOMBIE support!!!!!!
 
Exceptions raised:
XUNVALID_GUEST XUNVALID_TASK
some primitives are not implemented:
task_sleep, task_delay, guest_endcycle, guest_sleep, guest_delay
 
XACTIVATION
If a task is actiated through task_activate or guest_activate more than
one time
Restrictions & special features:
- This level doesn't manage the main task.
- At init time we have to specify:
. guarantee check
(when all task are created the system will check that the task_set
will not use more than the available bandwidth)
- A function to return the used bandwidth of the level is provided.
- Functions to return and reset the nact, wcet and dline miss counters
 
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __EDFACT_H__
#define __EDFACT_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
 
 
 
 
 
 
 
 
/*+ flags... +*/
#define EDFACT_ENABLE_GUARANTEE 1 /*+ Task Guarantee enabled +*/
#define EDFACT_ENABLE_ALL 1
 
#define EDFACT_FAILED_GUARANTEE 8 /*+ used in the module, unsettabl
in EDF_register_level... +*/
 
 
 
 
 
#define ELASTIC_HARD_PCLASS 0x0600
 
#define EDFACT_LEVELNAME "EDFACT base"
#define EDFACT_LEVEL_CODE 166
#define EDFACT_LEVEL_VERSION 1
 
 
/*+ Registration function:
int flags Options to be used in this level instance...
 
returns the level number at which the module has been registered.
+*/
LEVEL EDFACT_register_level(int flags);
 
/*+ Returns the used bandwidth of a level +*/
bandwidth_t EDFACT_usedbandwidth(LEVEL l);
 
/*+ returns respectively the number of dline, wcet or nact; -1 if error +*/
int EDFACT_get_dline_miss(PID p);
int EDFACT_get_wcet_miss(PID p);
int EDFACT_get_nact(PID p);
 
/*+ resets respectively the number of dline, wcet miss; -1 if error +*/
int EDFACT_reset_dline_miss(PID p);
int EDFACT_reset_wcet_miss(PID p);
 
#endif
 
/advdemos/branches/advdemos/edfact/makefile
0,0 → 1,16
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS= testact
 
include $(BASE)/config/example.mk
 
testact:
make -f $(SUBMAKE) APP=testact INIT= OTHEROBJS="initfile.o edfact.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
/advdemos/branches/advdemos/edfact/readme
0,0 → 1,31
EDFACT Scheduling Module
------------------------
by Paolo Gai 2001
 
 
Pisa, 6, Jun 2001
 
This Module implements a EDF scheduler.
 
It is very similar to the EDF Module distributed with the kernel sources,
except that:
- It does not support hard sporadic tasks
- It does not raise a deadline exception
- It does not raise a wcet violation exception
- Instead of raising an exception, the module simply COUNTS deadline misses
and wcet exaustions..
 
Since a large part of the applications use only periodic tasks, this Module
can be a great improvement because the application will not hang up at
the first exception!!! (and this happens frequently when switching to a
slower PC :-( )
 
I also wrote a simple test to show how the module works...
 
To use the Module in your applications, simply copy the edfact.c and edfact.h
into your application directory, and register edfact instead of the
tradictional edf...
 
For bugs, questions and comments please write to pj@sssup.it
 
Paolo
/advdemos/branches/advdemos/first/test1.c
0,0 → 1,247
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test1.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
this test shows a set of 5 tasks (+main+dummy+keyboard driver).
The first 4 tasks are scheduled by a EDFSTAR Module, whereas the
fifth one is a standard traditional EDF task. The 4 tasks uses a
budget of 10000/100000.
if edfstar.c is compiled with edfstar_printf3 active, a couple
(dline, curtime) is showed (in ms).
if cbsstar.c is compiled with cbsstar_printf3 active, the budget
replenishments are showed.
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level, edfstar_level, mybudget;
 
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
mybudget = CBSSTAR_setbudget(cbsstar_level, 10000, 100000);
edfstar_level = EDFSTAR_register_level(mybudget, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
//keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
 
void *star(void *arg)
{
int i,j;
 
for (i=0; i<5; i++) {
for (j=0; j<100000; j++);
cputc('°');
cputs((char *)arg);
task_endcycle();
}
 
return NULL;
}
 
void *edftask(void *arg)
{
int i,j;
 
for (i=0; i<5; i++) {
for (j=0; j<100000; j++);
cputc('°');
cputs((char *)arg);
task_endcycle();
}
 
return NULL;
}
 
void create1()
{
HARD_TASK_MODEL m1, m2;
PID p1a, p1b, p1c, p1d, p2;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_level(m1,2);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
hard_task_def_arg(m1,(void *)"a");
hard_task_def_mit(m1,10000);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"b");
hard_task_def_mit(m1,15000);
p1b = task_create("b", star, &m1, NULL);
if (p1b == -1) {
perror("Could not create task b ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"c");
hard_task_def_mit(m1,20000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"d");
hard_task_def_mit(m1,30000);
p1d = task_create("d", star, &m1, NULL);
if (p1d == -1) {
perror("Could not create task d ...");
sys_end();
}
 
hard_task_default_model(m2);
hard_task_def_mit(m2,50000); // the budget has dline 100,000!
hard_task_def_wcet(m2, 5000);
hard_task_def_arg(m2,(void *)"Û");
hard_task_def_group(m2,1);
hard_task_def_periodic(m2);
 
p2 = task_create("2", edftask, &m2, NULL);
if (p2 == -1) {
perror("Could not create task edf ...");
sys_end();
}
 
cprintf("stars=%d %d %d %d, star2=%d\n", p1a, p1b, p1c, p1d, p2);
 
group_activate(1);
}
 
int main(int argc, char **argv)
{
char c;
 
clear();
 
cprintf("Hello, world!\nPress ESC to end the demo...\n");
 
create1();
 
do {
c =keyb_getch(BLOCK);
} while (c != ESC);
 
cprintf("ESC pressed!");
 
sys_end();
 
return 0;
}
 
/advdemos/branches/advdemos/first/posixstar.h
0,0 → 1,142
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
 
/**
------------
CVS : $Id: posixstar.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
This file contains the scheduling module compatible with POSIX
specifications
 
Title:
POSIX version 1
 
Task Models Accepted:
NRT_TASK_MODEL - Non-Realtime Tasks
weight field is ignored
slice field is used to set the slice of a task, if it is !=0
policy field is ignored
inherit field is ignored
 
Description:
This module schedule his tasks following the POSIX specifications...
 
A task can be scheduled in a Round Robin way or in a FIFO way.
The tasks have also a priority field.
 
The slices can be different one task from one another.
 
The module can SAVE or SKIP activations
 
Exceptions raised:
XUNVALID_GUEST
This level doesn't support guests. When a guest operation
is called, the exception is raised.
 
Restrictions & special features:
- if specified, it creates at init time a task,
called "Main", attached to the function __init__().
- There must be only one module in the system that creates a task
attached to the function __init__().
- The level tries to guarantee that a RR task uses a "full" timeslice
before going to the queue tail. "full" means that a task can execute
a maximum time of slice+sys_tick due to the approx. done by
the Virtual Machine. If a task execute more time than the slice,
the next time it execute less...
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __POSIXSTAR_H__
#define __POSIXSTAR_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
//#define POSIXSTAR_DEBUG
 
/*+ Const: +*/
#define POSIXSTAR_MINIMUM_SLICE 1000 /*+ Minimum Timeslice +*/
#define POSIXSTAR_MAXIMUM_SLICE 500000 /*+ Maximum Timeslice +*/
 
/*+ Registration function:
TIME slice the slice for the Round Robin queue
int createmain 1 if the level creates the main task 0 otherwise
struct multiboot_info *mb used if createmain specified
 
returns the level number at which the module has been registered.
+*/
LEVEL POSIXSTAR_register_level(int budget, int master, TIME slice,
int prioritylevels);
 
/*+ this function forces the running task to go to his queue tail,
then calls the scheduler and changes the context
(it works only on the POSIX level) +*/
int POSIXSTAR_sched_yield(LEVEL l);
 
/* the following functions have to be called with interruptions DISABLED! */
 
/*+ this function returns the maximum level allowed for the POSIX level +*/
int POSIXSTAR_get_priority_max(LEVEL l);
 
/*+ this function returns the default timeslice for the POSIX level +*/
int POSIXSTAR_rr_get_interval(LEVEL l);
 
/*+ this functions returns some paramaters of a task;
policy must be NRT_RR_POLICY or NRT_FIFO_POLICY;
priority must be in the range [0..prioritylevels]
returns ENOSYS or ESRCH if there are problems +*/
int POSIXSTAR_getschedparam(LEVEL l, PID p, int *policy, int *priority);
 
/*+ this functions sets paramaters of a task +*/
int POSIXSTAR_setschedparam(LEVEL l, PID p, int policy, int priority);
 
#endif
 
/*
MANCANO
13.3.6 GETPRIORITYMin da mettere a 0
*/
/advdemos/branches/advdemos/first/cbsstar.c
0,0 → 1,674
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: cbsstar.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
Read CBSSTAR.h for general details.
 
Basically, a budget can be in 2 states:
- Active -> the budget queue is not empty
- Idle -> the budget queue is empty
 
The fact that a task into a budget is inserted into the master module depends
on the value of the remaining time the tasks can spend in the period.
 
The module does handle only one oslib event, used to enforce the
temporal isolation between buffers. Note that all is implemented
without using the CONTROL_CAP field.
 
Basically, for each budget there can be at most one task inserted
into the master level. Its deadline is modified according to the
usage of its capacity, that is, when a budget is exausted its
deadline is postponed.
 
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#include "cbsstar.h"
#include <ll/string.h>
 
#define ACTIVE 1
#define NOACTIVE 0
#define INIT 2
 
#define CBSSTAR_IDLE APER_STATUS_BASE
/*
* DEBUG stuffs begin
*/
 
//#define CBSSTAR_DEBUG
int event_monitor;
#ifdef CBSSTAR_DEBUG
 
 
static __inline__ void fake_printf(char *fmt, ...) {}
 
//#define cbsstar_printf kern_printf
//#define cbsstar_printf2 kern_printf
//#define cbsstar_printf3 kern_printf
 
#define cbsstar_printf fake_printf
#define cbsstar_printf2 fake_printf
#define cbsstar_printf3 fake_printf
 
#if 0
void cbsstar_printq(QQUEUE *q)
{
PID p;
kern_printf("[");
p = q->first;
kern_printf("->%d",p);
while (p != NIL) {
p = proc_table[p].next;
kern_printf("->%d",p);
}
kern_printf("]");
}
#else
static __inline__ void cbsstar_printq(QQUEUE *q) {}
#endif
 
#if 0
static __inline__ void cbsstar_printblob(int x) { if (x) cputc('±'); else cputc('Û'); }
#else
static __inline__ void cbsstar_printblob(int x) {}
#endif
 
#endif
 
/*
* DEBUG stuffs end
*/
/*+ Status used in the level +*/
#define CBSSTAR_WAIT APER_STATUS_BASE /*+ waiting the service +*/
 
/* this structure contains the status for a single budget */
struct budget_struct {
TIME Q; /* budget */
TIME T; /* period */
 
struct timespec dline; /* deadline */
int dline_timer; /* oslib event for budget reactivation*/
int avail; /* current budget */
 
PID current; /* the task currently put in execution */
int flags;
IQUEUE tasks; /* a FIFO queue for the tasks handled
using the budget */
};
 
typedef struct {
level_des l; /* the standard level descriptor */
 
struct budget_struct *b; /* the budgets! */
int n; /* the maximum index for the budgets */
int freebudgets; /* number of free budgets; starts from n */
 
int tb[MAX_PROC]; /* link task->budget (used in guest_end) */
 
bandwidth_t U; /*+ the used bandwidth by the server +*/
 
int cap_lev;
 
PID on_shadow;
 
LEVEL scheduling_level;
 
} CBSSTAR_level_des;
 
 
static void CBSSTAR_deadline_timer_hardreservation(void *a)
{
struct budget_struct *b = a;
struct timespec t;
//kern_printf("*********** %d", b->dline_timer);
b->dline_timer=NIL;
/* we modify the deadline according to rule 4 ... */
/* there is a while because if the wcet is << than the system tick
we need to postpone the deadline many times */
if (b->avail<=0) {
b->avail += b->Q;
if (b->avail>b->Q) b->avail=b->Q;
 
//kern_printf("budget recharge %d", b);
}
if (b->avail>0) b->flags=ACTIVE;
/* avail may be <0 because a task executed via a shadow fo many time
b->current == NIL only if the prec task was finished and there
was not any other task to be put in the ready queue
... we are now activating the next task */
if (b->current == NIL && b->flags) {
if (iq_query_first(&(b->tasks)) != NIL) {
//struct timespec t;
CBSSTAR_level_des *lev;
PID p;
JOB_TASK_MODEL job;
//kern_gettime(&t);
//TIMESPEC_ASSIGN(&b->dline, &schedule_time);
//ADDUSEC2TIMESPEC(b->T, &b->dline);
kern_gettime(&t);
TIMESPEC_ASSIGN(&b->dline, &t);
ADDUSEC2TIMESPEC(b->T, &b->dline);
 
p = iq_getfirst(&(b->tasks));
b->current=p;
lev = (CBSSTAR_level_des *)(level_table[proc_table[p].task_level]);
//kern_printf("reinsert task p = %d lev = %d ",p,proc_table[p].task_level);
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, b->dline);
job_task_def_noexc(job);
//kern_printf("(CR:iact p%d %ld.%ld av=%d)",p,b->dline.tv_sec,b->dline.tv_nsec/1000, b->avail);
//kern_printf("**");
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
event_need_reschedule();
}
} else
if (b->current !=NIL && b->avail>0) {
kern_printf("(cap&nil ");
}
if (b->flags==NOACTIVE && b->dline_timer!=NIL){
kern_gettime(&t);
TIMESPEC_ASSIGN(&b->dline, &t);
ADDUSEC2TIMESPEC(b->T, &b->dline);
b->dline_timer=kern_event_post(&b->dline, CBSSTAR_deadline_timer_hardreservation, b);
event_monitor=b->dline_timer;
//kern_printf("(dline hard %ld.%ld ev %d)",b->dline.tv_sec,b->dline.tv_nsec/1000, b->dline_timer);
}
}
static void CBSSTAR_activation(CBSSTAR_level_des *lev,
PID p,
struct timespec *acttime)
{
JOB_TASK_MODEL job;
struct budget_struct *b = &lev->b[lev->tb[p]];
/* we have to check if the deadline and the wcet are correct before
activating a new task or an old task... */
 
/* check 1: if the deadline is before than the actual scheduling time */
 
/* check 2: if ( avail_time >= (cbs_dline - acttime)* (wcet/period) )
(rule 7 in the CBS article!) */
TIME t;
struct timespec t2,t3;
 
t = (b->T * b->avail) / b->Q;
t3.tv_sec = t / 1000000;
t3.tv_nsec = (t % 1000000) * 1000;
 
SUBTIMESPEC(&b->dline, acttime, &t2);
if (/* 1 */ TIMESPEC_A_LT_B(&b->dline, acttime) ||
/* 2 */ TIMESPEC_A_GT_B(&t3, &t2) ) {
TIMESPEC_ASSIGN(&b->dline, acttime);
ADDUSEC2TIMESPEC(b->T, &b->dline);
}
/* and the capacity */
if (b->flags==INIT) {
b->avail = b->Q;
b->flags=ACTIVE;
}
 
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf3("±%d±",lev->tb[p]);
cbsstar_printblob(lev->tb[p]);
#endif
//}
//#endif
 
/* record the current task inserted in the master module */
b->current = p;
 
//#ifdef CBSSTAR_DEBUG
//kern_printf("(CA:iact p%d %ld.%ld av=%d at=%ld.%ld)",p,b->dline.tv_sec,b->dline.tv_nsec/1000, b->avail, acttime->tv_sec, acttime->tv_nsec/1000);
//#endif
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, b->dline);
job_task_def_noexc(job);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
//b->dline_timer=kern_event_post(&b->dline, CBSSTAR_deadline_timer_hardreservation, b);
}
 
static void CBSSTAR_account_capacity(CBSSTAR_level_des *lev, PID p)
{
struct timespec ty;
TIME tx;
struct budget_struct *b = &lev->b[lev->tb[p]];
TIME t;
struct timespec t2,t3, acttime;
 
if (lev->cap_lev!=NIL && b->current==p) {
kern_event_delete(lev->cap_lev);
lev->cap_lev=NIL;
}
 
kern_gettime(&acttime);
t = (b->T * b->avail) / b->Q;
t3.tv_sec = t / 1000000;
t3.tv_nsec = (t % 1000000) * 1000;
 
SUBTIMESPEC(&b->dline, &acttime, &t2);
SUBTIMESPEC(&schedule_time, &cap_lasttime, &ty);
tx = TIMESPEC2USEC(&ty);
lev->b[lev->tb[p]].avail -= tx;
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf2("(C:cap p%d av=%d)", p, lev->b[lev->tb[p]].avail);
#endif
if (lev->b[lev->tb[p]].avail<=0 || TIMESPEC_A_GT_B(&t3, &t2)) lev->b[lev->tb[p]].flags=NOACTIVE;
 
if ( TIMESPEC_A_LT_B(&b->dline, &schedule_time) ) {
/* we modify the deadline ... */
TIMESPEC_ASSIGN(&b->dline, &schedule_time);
ADDUSEC2TIMESPEC(b->T, &b->dline);
}
 
//if (b->flags==NOACTIVE && b->dline_timer!=NIL)
// kern_printf("flags %d, dline_timer %d", b->flags, b->dline_timer);
if (b->flags==NOACTIVE && b->dline_timer==NIL) {
b->dline_timer=kern_event_post(&b->dline, CBSSTAR_deadline_timer_hardreservation, b);
event_monitor=b->dline_timer;
//kern_printf("(dline %ld.%ld ev %d)",b->dline.tv_sec,b->dline.tv_nsec/1000, b->dline_timer);
}
 
}
 
 
/* The on-line guarantee is enabled only if the appropriate flag is set... */
static int CBSSTAR_public_guarantee(LEVEL l, bandwidth_t *freebandwidth)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf("(C:gua)");
#endif
 
if (*freebandwidth >= lev->U) {
*freebandwidth -= lev->U;
return 1;
}
else
return 0;
}
 
static void capacity_handler(void *l)
{
//kern_printf("!");
CBSSTAR_level_des *lev =l;
lev->cap_lev=NIL;
event_need_reschedule();
}
 
static int CBSSTAR_private_eligible(LEVEL l, PID p)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
struct budget_struct *b = &lev->b[lev->tb[p]];
JOB_TASK_MODEL job;
 
#ifdef CBSSTAR_DEBUG
//kern_printf("(C:eli %d",p);
#endif
 
/* we have to check if the deadline and the wcet are correct...
if the CBSSTAR level schedules in background with respect to others
levels, there can be the case in witch a task is scheduled by
schedule_time > CBSSTAR_deadline; in this case (not covered in the
article because if there is only the standard scheduling policy
this never apply) we reassign the deadline */
if (b->current==p) {
if ( TIMESPEC_A_LT_B(&b->dline, &schedule_time)) {
if (lev->cap_lev!=NIL) {
kern_event_delete(lev->cap_lev);
lev->cap_lev=NIL;
}
/* we kill the current activation */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
/* we modify the deadline ... */
TIMESPEC_ASSIGN(&b->dline, &schedule_time);
ADDUSEC2TIMESPEC(b->T, &b->dline);
 
/* and the capacity */
b->avail = b->Q;
b->flags=ACTIVE;
 
if (b->dline_timer!=NIL) {
kern_event_delete(b->dline_timer);
b->dline_timer=NIL;
}
//#ifdef CBSSTAR_DEBUG
//kern_printf(" %ld.%ld av=%d)",b->dline.tv_sec,b->dline.tv_nsec/1000, b->Q);
//cbsstar_printf3("±%d±",lev->tb[p]);
//cbsstar_printblob(lev->tb[p]);
//#endif
 
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, b->dline);
job_task_def_noexc(job);
//kern_printf("(CE:iact p%d %ld.%ld av=%d)",p,b->dline.tv_sec,b->dline.tv_nsec/1000, b->avail);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
//kern_printf("task %d, avail %d", p, b->avail);
return -1;
}
}
#ifdef CBSSTAR_DEBUG
cbsstar_printf(")");
#endif
 
return 0;
}
 
static void CBSSTAR_private_insert(LEVEL l, PID p, TASK_MODEL *m)
{
/* A task has been activated for some reason. Basically, the task is
inserted in the queue if the queue is empty, otherwise the task is
inserted into the master module, and an oslib event is posted. */
 
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
BUDGET_TASK_MODEL *budget;
 
if (m->pclass != BUDGET_PCLASS ||
(m->level != 0 && m->level != l)) {
kern_raise(XINVALID_TASK, p);
return;
}
budget = (BUDGET_TASK_MODEL *)m;
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf("(C:gcr %d b%d", p, budget->b);
#endif
 
lev->tb[p] = budget->b;
 
if (lev->b[budget->b].current == NIL && lev->b[budget->b].flags ) {
/* This is the first task in the budget,
the task have to be inserted into the master module */
struct timespec t;
kern_gettime(&t);
CBSSTAR_activation(lev,p,&t);
} else {
/* The budget is not empty, another task is already into the
master module, so the task is inserted at the end of the budget
queue */
iq_insertlast(p,&lev->b[budget->b].tasks);
//#ifdef CBSSTAR_DEBUG
//kern_printf(" ilast flag %d task %d",lev->b[budget->b].flags,lev->b[budget->b].current);
// cbsstar_printq(&lev->b[budget->b].tasks);
//#endif
}
#ifdef CBSSTAR_DEBUG
cbsstar_printf(")");
#endif
}
 
static void CBSSTAR_private_extract(LEVEL l, PID p)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
 
//#ifdef CBSSTAR_DEBUG
//kern_printf("(C:gend p%d c%d av=%d)", p, lev->b[lev->tb[p]].current, lev->b[lev->tb[p]].avail);
//cbsstar_printq(&lev->b[lev->tb[p]].tasks);
//#endif
 
/* a task is removed from execution for some reasons. It must be
that it is the first in its budget queue (only the first task in
a budget queue is put into execution!) */
 
/* remove the task from execution (or from the ready queue) */
if (lev->b[lev->tb[p]].current == p) {
 
CBSSTAR_account_capacity(lev,p);
/* remove the task from the master module */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
 
#ifdef CBSSTAR_DEBUG
cbsstar_printq(&lev->b[lev->tb[p]].tasks);
#endif
 
/* check if the buffer has someone else to schedule */
if (iq_query_first(&lev->b[lev->tb[p]].tasks) == NIL) {
/* the buffer has no tasks! */
lev->b[lev->tb[p]].current = NIL;
}
else if (lev->b[lev->tb[p]].flags) {
/* if so, insert the new task into the master module */
PID n;
struct timespec t;
kern_gettime(&t);
n = iq_getfirst(&lev->b[lev->tb[p]].tasks);
//#ifdef CBSSTAR_DEBUG
//kern_printf("{p%d n%d}",p,n);
//#endif
CBSSTAR_activation(lev,n,&t); // it modifies b[lev->tb[p]].current
}
else
lev->b[lev->tb[p]].current=NIL;
 
}
else {
iq_extract(p, &lev->b[lev->tb[p]].tasks);
}
}
 
static void CBSSTAR_private_dispatch(LEVEL l, PID p, int nostop)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
struct timespec ty;
 
//#ifdef CBSSTAR_DEBUG
//kern_printf("(C:gdisp p%d c%d av=%d)", p, lev->b[lev->tb[p]].current, lev->b[lev->tb[p]].avail);
// cbsstar_printq(&lev->b[lev->tb[p]].tasks);
//#endif
 
/* the current task (that is the only one inserted in the master module
for the corresponding budget) is dispatched. Note that the current
task is not inserted in any FIFO queue, so the task does not have to
be extracted! */
 
/* ... then, we dispatch it to the master level */
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
 
/* ...and finally, we have to post a capacity event */
if (!nostop) {
TIMESPEC_ASSIGN(&ty, &schedule_time);
ADDUSEC2TIMESPEC(lev->b[lev->tb[p]].avail,&ty);
lev->cap_lev = kern_event_post(&ty,capacity_handler, lev);
}
}
 
static void CBSSTAR_private_epilogue(LEVEL l, PID p)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
struct budget_struct *b = &lev->b[lev->tb[p]];
 
 
//#ifdef CBSSTAR_DEBUG
//kern_printf("(C:gepi %d %d",p, b->current);
//#endif
 
if (p==b->current) {
CBSSTAR_account_capacity(lev,p);
 
// L'evento di capacità va cancellato perchè sarà ripristinato nella successiva dispatch
/* we have to check if the capacity is still available */
if (b->flags) {
/* there is capacity available, maybe it is simply a preemption;
the task have to return to the ready queue */
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
#ifdef CBSSTAR_DEBUG
//kern_printf("(ep *av=%d", b->avail);
#endif
} else {
/* we kill the current activation */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
//kern_printf("extract");
iq_insertfirst(p, &b->tasks);
proc_table[p].status = CBSSTAR_IDLE;
b->current = NIL;
//kern_printf("budget finish %d", b);
}
#ifdef CBSSTAR_DEBUG
cbsstar_printf(")");
#endif
}
 
}
 
/* Registration functions }*/
 
/*+ Registration function:
int flags the init flags ... see CBSSTAR.h +*/
LEVEL CBSSTAR_register_level(int n, LEVEL master)
{
LEVEL l; /* the level that we register */
CBSSTAR_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf("CBSSTAR_register_level\n");
#endif
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(CBSSTAR_level_des));
 
lev = (CBSSTAR_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.private_insert = CBSSTAR_private_insert;
lev->l.private_extract = CBSSTAR_private_extract;
lev->l.private_eligible = CBSSTAR_private_eligible;
lev->l.private_dispatch = CBSSTAR_private_dispatch;
lev->l.private_epilogue = CBSSTAR_private_epilogue;
 
lev->l.public_guarantee = CBSSTAR_public_guarantee;
 
/* fill the CBSSTAR descriptor part */
lev->b = (struct budget_struct *)kern_alloc(sizeof(struct budget_struct)*n);
 
for (i=0; i<n; i++) {
lev->b[i].Q = 0;
lev->b[i].T = 0;
NULL_TIMESPEC(&lev->b[i].dline);
lev->b[i].dline_timer = NIL;
lev->b[i].avail = 0;
lev->b[i].current = -1;
lev->b[i].flags=INIT;
iq_init(&lev->b[i].tasks, &freedesc, 0);
}
 
lev->n = n;
lev->freebudgets = 0;
 
for (i=0; i<MAX_PROC; i++)
lev->tb[i] = NIL;
 
lev->U = 0;
lev->cap_lev=NIL;
lev->scheduling_level = master;
lev->on_shadow=NIL;
 
return l;
}
 
int CBSSTAR_setbudget(LEVEL l, TIME Q, TIME T)
{
CBSSTAR_level_des *lev = (CBSSTAR_level_des *)(level_table[l]);
 
#ifdef CBSSTAR_DEBUG
cbsstar_printf("(C:sbud)");
#endif
 
if (lev->freebudgets != lev->n) {
bandwidth_t b;
b = (MAX_BANDWIDTH / T) * Q;
/* really update lev->U, checking an overflow... */
if (Q< T && MAX_BANDWIDTH - lev->U > b) {
int r = lev->freebudgets; // the return value
lev->U += b;
lev->freebudgets++;
lev->b[r].Q = Q;
lev->b[r].T = T;
return r;
}
else
return -2;
}
else
return -1;
}
/advdemos/branches/advdemos/first/test2.c
0,0 → 1,241
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test2.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
The purpose of this test is to show that two budgets with different
period and capacity schedules correctly.
 
4 periodic tasks are involved
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level, edfstar_level, edfstar_level2, mybudget, mybudget2;
clear();
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
 
mybudget = CBSSTAR_setbudget(cbsstar_level, 1000, 50000);
edfstar_level = EDFSTAR_register_level(mybudget, cbsstar_level);
 
mybudget2 = CBSSTAR_setbudget(cbsstar_level, 10000, 25000);
edfstar_level2 = EDFSTAR_register_level(mybudget2, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
cprintf("edfstar_level=%d, edfstar_level2=%d\n",
edfstar_level,edfstar_level2);
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
 
void *star(void *arg)
{
int i,j,z;
 
for (i=0; i<100; i++) {
for (z=0; z<5; z++) {
for (j=0; j<60000; j++);
cputs((char *)arg);
}
task_endcycle();
}
 
return NULL;
}
 
// version for the "slow" budget
void *slow(void *arg)
{
int i,j,z;
 
for (i=0; i<15; i++) {
for (z=0; z<5; z++) {
for (j=0; j<200000; j++);
cputs((char *)arg);
}
task_endcycle();
}
 
return NULL;
}
 
void create1()
{
HARD_TASK_MODEL m1;
PID p1a, p1b, p1c, p1d;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
 
 
 
hard_task_def_level(m1,2);
 
hard_task_def_arg(m1,(void *)".");
hard_task_def_mit(m1,5000);
p1a = task_create("a", slow, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)",");
hard_task_def_mit(m1,5000);
p1b = task_create("b", slow, &m1, NULL);
if (p1b == -1) {
perror("Could not create task b ...");
sys_end();
}
 
 
 
 
hard_task_def_level(m1,3);
 
hard_task_def_arg(m1,(void *)"o");
hard_task_def_mit(m1,5000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"O");
hard_task_def_mit(m1,5000);
p1d = task_create("d", star, &m1, NULL);
if (p1d == -1) {
perror("Could not create task d ...");
sys_end();
}
 
group_activate(1);
}
 
int main(int argc, char **argv)
{
char c;
 
cprintf("Hello, world!");
 
create1();
 
do {
c =keyb_getch(BLOCK);
} while (c != ESC);
 
cprintf("ESC pressed!");
 
sys_end();
 
return 0;
}
 
/advdemos/branches/advdemos/first/test3.c
0,0 → 1,213
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test3.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
The purpose of this test is to show that two budgets with different
period and budgets schedules correctly.
 
2 never ending tasks are involved
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level, edfstar_level, edfstar_level2, mybudget, mybudget2;
clear();
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
 
mybudget = CBSSTAR_setbudget(cbsstar_level, 2000, 50000);
edfstar_level = EDFSTAR_register_level(mybudget, cbsstar_level);
 
mybudget2 = CBSSTAR_setbudget(cbsstar_level, 10000, 25000);
edfstar_level2 = EDFSTAR_register_level(mybudget2, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
cprintf("edfstar_level=%d, edfstar_level2=%d\n",
edfstar_level,edfstar_level2);
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
#include <semaphore.h>
 
sem_t s;
 
void *star(void *arg)
{
int j,z;
 
for (;;) {
for (z=0; z<5; z++) {
for (j=0; j<60000; j++);
sem_wait(&s);
cputs((char *)arg);
sem_post(&s);
}
}
 
return NULL;
}
 
 
void create1()
{
HARD_TASK_MODEL m1;
PID p1a, p1c;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
 
 
 
hard_task_def_level(m1,2);
 
hard_task_def_arg(m1,(void *)"O");
hard_task_def_mit(m1,5000);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
 
hard_task_def_level(m1,3);
 
hard_task_def_arg(m1,(void *)".");
hard_task_def_mit(m1,5000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
group_activate(1);
}
 
void endfun(KEY_EVT *k)
{
cprintf("ESC pressed!");
 
sys_end();
}
 
int main(int argc, char **argv)
{
KEY_EVT k;
 
sem_init(&s,0,1);
 
k.flag = 0;
k.scan = KEY_ESC;
k.ascii = 27;
keyb_hook(k,endfun);
 
create1();
 
return 0;
}
 
/advdemos/branches/advdemos/first/iqueue.h
0,0 → 1,172
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: iqueue.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
/*
IQUEUEs
 
This file contains functions that helps to manage task queues.
 
These functions are different from the functions that manages the
QUEUE and QQUEUE types. In particular, these functions no more relies
on the prev & next fields of the task descriptor. In that way, tasks
can be inserted in more than one queue at a time.
 
Basically, an IQUEUE has an "I"nternal prev/next structure, that may
be shared between one or more queue. Of course, the user MUST
guarantee that the same task will not be inserted in two IQUEUEs that
share the same prev/next buffer.
 
The queue insertion is made by the following functions:
iq_insert -> insertion based on the priority field.
iq_timespec_insert -> same as above but use the timespec_priority field
iq_insertfirst -> insert in the first position of the queue
*/
 
#include <kernel/const.h>
#include <kernel/types.h>
#include <sys/types.h>
 
#define IQUEUE_NO_PRIORITY 1
#define IQUEUE_NO_TIMESPEC 2
 
struct IQUEUE_shared {
PID prev[MAX_PROC];
PID next[MAX_PROC];
struct timespec *timespec_priority;
DWORD *priority;
};
 
typedef struct {
PID first;
PID last;
struct IQUEUE_shared *s;
} IQUEUE;
 
 
 
/* Internal queue initialization:
 
share = &x -> the internal data structure of the IQUEUE x is used
to enqueue the tasks.
 
share = NULL -> an internal data structure to handle prev/next
pairs is dynamically allocated (The amount of
memory that is allocated can be reduced using the
flags).
 
flags can be used to reduce the memory usage of an IQUEUE when share=NULL:
IQUEUE_NO_PRIORITY -> the iqueue do not provide internally a priority field
IQUEUE_NO_TIMESPEC -> the iqueue do not provide internally a timespec field
 
- note that, if these flags are used, the corresponding insert
functions will not work!
- the default value for the flags is, of course, 0
*/
void iq_init (IQUEUE *q, IQUEUE *share, int flags);
 
/* Queue insert functions:
 
- inserts a p into the q. p must not be already inserted into q.
- four versions of the function;
- iq_priority_insert -> ordered insertion using the priority field
- iq_timespec_insert -> ordered insertion using the timespec field
- iq_insertfirst -> insert at the first position of the queue
- iq_insertlast -> insert at the last position of the queue
*/
void iq_priority_insert (PID p, IQUEUE *q);
void iq_timespec_insert (PID p, IQUEUE *q);
void iq_insertfirst (PID p, IQUEUE *q);
void iq_insertlast (PID p, IQUEUE *q);
 
/* Queue extract functions:
 
- extracts a task p from the queue q.
- three versions of the function;
- iq_extract -> extracts given a task p
(that must be inserted in the queue)
 
- iq_getfirst -> extracts the first task in the queue,
NIL if the queue is empty
- iq_getlast -> extracts the last task in the queue,
NIL if the queue is empty
 
*/
void iq_extract (PID p, IQUEUE *q);
PID iq_getfirst ( IQUEUE *q);
PID iq_getlast ( IQUEUE *q);
 
 
/* Queue query functions:
 
The first two functions return the first and the last task in the queue,
NIL if the queue is empty.
 
The second two functions can be used to get/set the priority or the
timespec field used when queuing.
*/
static __inline__ PID iq_queryfirst(IQUEUE *q)
{
return q->first;
}
 
static __inline__ PID iq_querylast(IQUEUE *q)
{
return q->last;
}
 
static __inline__ struct timespec *iq_query_timespec(PID p, IQUEUE *q)
{
return &q->s->timespec_priority[p];
}
 
static __inline__ DWORD *iq_query_priority (PID p, IQUEUE *q)
{
return &q->s->priority[p];
}
/advdemos/branches/advdemos/first/test4.c
0,0 → 1,231
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test4.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
The purpose of this test is to show that two budgets with different
period and budgets schedules correctly.
2 never ending tasks are involved
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level;
int edfstar_level, edfstar_level2, edfstar_level3;
int mybudget, mybudget2;
 
clear();
 
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
 
mybudget = CBSSTAR_setbudget(cbsstar_level, 2000, 50000);
edfstar_level = EDFSTAR_register_level(mybudget, cbsstar_level);
 
mybudget2 = CBSSTAR_setbudget(cbsstar_level, 10000, 25000);
edfstar_level2 = EDFSTAR_register_level(mybudget2, cbsstar_level);
edfstar_level3 = EDFSTAR_register_level(mybudget2, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
cprintf("edfstar_level=%d, edfstar_level2=%d\n",
edfstar_level,edfstar_level2);
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
//keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
#include <semaphore.h>
 
sem_t s;
 
void *star(void *arg)
{
int j,z;
 
for (;;) {
for (z=0; z<50; z++) {
for (j=0; j<60000; j++);
// sem_wait(&s);
cputs((char *)arg);
// sem_post(&s);
}
task_endcycle();
}
 
return NULL;
}
 
 
void create1()
{
HARD_TASK_MODEL m1;
PID p1a, p1b, p1c;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
 
 
 
hard_task_def_level(m1,2);
 
hard_task_def_arg(m1,(void *)"O");
hard_task_def_mit(m1,5000);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
 
hard_task_def_level(m1,3);
 
hard_task_def_arg(m1,(void *)".");
hard_task_def_mit(m1,5000);
p1b = task_create("b", star, &m1, NULL);
if (p1b == -1) {
perror("Could not create task c ...");
sys_end();
}
 
hard_task_def_level(m1,4);
 
hard_task_def_arg(m1,(void *)",");
hard_task_def_mit(m1,5000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
group_activate(1);
}
 
void endfun(KEY_EVT *k)
{
cprintf("ESC pressed!");
 
sys_end();
}
 
int main(int argc, char **argv)
{
KEY_EVT k;
 
sem_init(&s,0,1);
 
k.flag = 0;
k.scan = KEY_ESC;
k.ascii = 27;
keyb_hook(k,endfun);
 
create1();
 
return 0;
}
 
/advdemos/branches/advdemos/first/test5.c
0,0 → 1,248
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test5.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
The purpose of this test is to show that two budgets with different
period and budgets schedules correctly.
2 never ending tasks are involved
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level;
int edfstar_level, edfstar_level2, edfstar_level3;
int mybudget, mybudget2;
 
clear();
 
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
 
mybudget = CBSSTAR_setbudget(cbsstar_level, 2000, 50000);
edfstar_level = EDFSTAR_register_level(mybudget, cbsstar_level);
 
mybudget2 = CBSSTAR_setbudget(cbsstar_level, 10000, 25000);
edfstar_level2 = EDFSTAR_register_level(mybudget2, cbsstar_level);
edfstar_level3 = EDFSTAR_register_level(mybudget2, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
cprintf("edfstar_level=%d, edfstar_level2=%d\n",
edfstar_level,edfstar_level2);
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
CBS_register_level(CBS_ENABLE_ALL, edfstar_level3);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
//keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
#include <semaphore.h>
 
sem_t s;
 
void *star(void *arg)
{
int j,z;
 
for (;;) {
for (z=0; z<50; z++) {
for (j=0; j<60000; j++);
// sem_wait(&s);
cputs((char *)arg);
// sem_post(&s);
}
task_endcycle();
}
 
return NULL;
}
 
 
void create1()
{
HARD_TASK_MODEL m1;
SOFT_TASK_MODEL ms;
PID p1a, p1b, p1c, p2;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
 
 
 
hard_task_def_level(m1,2);
 
hard_task_def_arg(m1,(void *)"O");
hard_task_def_mit(m1,5000);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
 
hard_task_def_level(m1,3);
 
hard_task_def_arg(m1,(void *)".");
hard_task_def_mit(m1,50000);
p1b = task_create("b", star, &m1, NULL);
if (p1b == -1) {
perror("Could not create task c ...");
sys_end();
}
 
hard_task_def_level(m1,4);
 
hard_task_def_arg(m1,(void *)",");
hard_task_def_mit(m1,50000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
soft_task_default_model(ms);
soft_task_def_met(ms, 5000);
soft_task_def_period(ms, 30000);
soft_task_def_group(ms,1);
soft_task_def_periodic(ms);
soft_task_def_level(ms,8);
soft_task_def_arg(ms,(void *)"X");
p2 = task_create("S", star, &ms, NULL);
if (p2 == -1) {
perror("Could not create task S ...");
sys_end();
}
 
group_activate(1);
}
 
void endfun(KEY_EVT *k)
{
cprintf("ESC pressed!");
 
sys_end();
}
 
int main(int argc, char **argv)
{
KEY_EVT k;
 
sem_init(&s,0,1);
 
k.flag = 0;
k.scan = KEY_ESC;
k.ascii = 27;
keyb_hook(k,endfun);
 
create1();
 
return 0;
}
 
/advdemos/branches/advdemos/first/test6.c
0,0 → 1,248
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test6.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
this test shows a set of 5 tasks (+main+dummy+keyboard driver).
The first 4 tasks are scheduled by a RMSTAR Module, whereas the
fifth one is a standard traditional EDF task. The 4 tasks uses a
budget of 10000/100000.
if edfstar.c is compiled with edfstar_printf3 active, a couple
(dline, curtime) is showed (in ms).
if cbsstar.c is compiled with cbsstar_printf3 active, the budget
replenishments are showed.
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "rmstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level, rmstar_level, mybudget;
 
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
mybudget = CBSSTAR_setbudget(cbsstar_level, 10000, 100000);
rmstar_level = RMSTAR_register_level(mybudget, cbsstar_level);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
//keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
 
void *star(void *arg)
{
int i,j;
 
for (i=0; i<5; i++) {
for (j=0; j<100000; j++);
cputc('°');
cputs((char *)arg);
task_endcycle();
}
 
return NULL;
}
 
void *edftask(void *arg)
{
int i,j;
 
for (i=0; i<5; i++) {
for (j=0; j<100000; j++);
cputc('°');
cputs((char *)arg);
task_endcycle();
}
 
return NULL;
}
 
void create1()
{
HARD_TASK_MODEL m1, m2;
PID p1a, p1b, p1c, p1d, p2;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_level(m1,2);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
 
hard_task_def_arg(m1,(void *)"a");
hard_task_def_mit(m1,10000);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"b");
hard_task_def_mit(m1,15000);
p1b = task_create("b", star, &m1, NULL);
if (p1b == -1) {
perror("Could not create task b ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"c");
hard_task_def_mit(m1,20000);
p1c = task_create("c", star, &m1, NULL);
if (p1c == -1) {
perror("Could not create task c ...");
sys_end();
}
 
hard_task_def_arg(m1,(void *)"d");
hard_task_def_mit(m1,30000);
p1d = task_create("d", star, &m1, NULL);
if (p1d == -1) {
perror("Could not create task d ...");
sys_end();
}
 
hard_task_default_model(m2);
hard_task_def_mit(m2,50000); // the budget has dline 100,000!
hard_task_def_wcet(m2, 5000);
hard_task_def_arg(m2,(void *)"Û");
hard_task_def_group(m2,1);
hard_task_def_periodic(m2);
 
p2 = task_create("2", edftask, &m2, NULL);
if (p2 == -1) {
perror("Could not create task edf ...");
sys_end();
}
 
cprintf("stars=%d %d %d %d, star2=%d\n", p1a, p1b, p1c, p1d, p2);
 
group_activate(1);
}
 
int main(int argc, char **argv)
{
char c;
 
clear();
 
cprintf("Hello, world!");
 
create1();
 
do {
c =keyb_getch(BLOCK);
} while (c != ESC);
 
cprintf("ESC pressed!");
 
sys_end();
 
return 0;
}
 
/advdemos/branches/advdemos/first/test7.c
0,0 → 1,338
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: test7.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
this test shows a set of 5 tasks (+main+dummy+keyboard driver).
The first 4 tasks are scheduled by a EDFSTAR Module, whereas the
fifth one is a standard traditional EDF task. The 4 tasks uses a
budget of 10000/100000.
if edfstar.c is compiled with edfstar_printf3 active, a couple
(dline, curtime) is showed (in ms).
if cbsstar.c is compiled with cbsstar_printf3 active, the budget
replenishments are showed.
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "posixstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "modules/pi.h"
#include "modules/nop.h"
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int cbsstar_level, posixstar_level, mybudget, mybudget1, posixstar_level1;
 
EDF_register_level(EDF_ENABLE_ALL);
 
cbsstar_level = CBSSTAR_register_level(3, 0);
mybudget = CBSSTAR_setbudget(cbsstar_level, 15000, 30000);
mybudget1 = CBSSTAR_setbudget(cbsstar_level, 14000, 56000);
posixstar_level = POSIXSTAR_register_level(mybudget, cbsstar_level, 3000,1);
posixstar_level1 = POSIXSTAR_register_level(mybudget1, cbsstar_level, 5000,1);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
// for the keyboard...
//CBS_register_level(CBS_ENABLE_ALL, 0);
 
//SEM_register_module();
PI_register_module();
NOP_register_module();
return TICK;
}
 
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
//CABS_register_module();
//keyb_def_map(kparms,itaMap);
//KEYB_init(&kparms);
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
#include <semaphore.h>
 
mutex_t s;
 
void *star(void *arg)
{
int j;
for (;;) {
for (j=0; j<5000; j++);
//sem_wait(&s);
mutex_lock(&s);
cputc('°');
cputs((char *)arg);
mutex_unlock(&s);
//kern_printf("ril");
//sem_post(&s);
//task_endcycle();
}
 
return NULL;
}
 
void *edftask(void *arg)
{
int i,j;
while(1) {
for (i=0;i<5; i++) {
for (j=0; j<10; j++);
//sem_wait(&s);
//mutex_lock(&s);
cputc('°');
cputs((char *)arg);
//mutex_unlock(&s);
//sem_post(&s);
}
 
task_endcycle();
}
 
return NULL;
}
 
 
void create1()
{
int i;
NRT_TASK_MODEL m1;
HARD_TASK_MODEL m2;
PID p1a, p1b, p1c[20],p2,p3;
struct timespec fineprg;
nrt_task_default_model(m1);
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
nrt_task_def_arg(m1,(void *)"A");
nrt_task_def_weight(m1,0);
p1a = task_create("a",star,&m1,NULL);
if (p1a == -1) {
perror("Could not create task <Write>");
sys_abort(-1);
}
nrt_task_def_arg(m1,(void *)"B");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
p1b = task_create("b", star, &m1, NULL);
if (p1b == -1) {
perror("Could not create task b ...");
sys_end();
}
nrt_task_def_arg(m1,(void *)"1");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
 
p1c[5] = task_create("1", star, &m1, NULL);
if (p1c[5] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
nrt_task_def_arg(m1,(void *)"C");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
p1c[4] = task_create("c", star, &m1, NULL);
if (p1c[4] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
nrt_task_def_arg(m1,(void *)"D");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
p1c[5] = task_create("d", star, &m1, NULL);
if (p1c[5] == -1) {
perror("Could not create task b ...");
sys_end();
}
nrt_task_def_arg(m1,(void *)"E");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
p1c[0] = task_create("e", star, &m1, NULL);
if (p1c[0] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
nrt_task_def_arg(m1,(void *)"F");
p1c[1] = task_create("f", star, &m1, NULL);
if (p1c[1] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
nrt_task_def_arg(m1,(void *)"G");
nrt_task_def_group(m1, 1);
nrt_task_def_level(m1,2);
p1c[2] = task_create("g", star, &m1, NULL);
if (p1c[2] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
nrt_task_def_arg(m1,(void *)"H");
p1c[3] = task_create("h", star, &m1, NULL);
if (p1c[3] == -1) {
perror("Could not create task b ...");
sys_end();
}
nrt_task_def_arg(m1,(void *)"I");
p1c[4] = task_create("h", star, &m1, NULL);
if (p1c[4] == -1) {
perror("Could not create task b ...");
sys_end();
}
 
hard_task_default_model(m2);
hard_task_def_ctrl_jet(m2);
hard_task_def_mit(m2,32000); // the budget has dline 100,000!
hard_task_def_wcet(m2, 3000);
hard_task_def_arg(m2,(void *)"X");
hard_task_def_group(m2,1);
hard_task_def_periodic(m2);
p2 = task_create("2", edftask, &m2, NULL);
if (p2 == -1) {
perror("Could not create task edf ...");
sys_end();
}
 
hard_task_def_mit(m2,32000); // the budget has dline 100,000!
hard_task_def_wcet(m2, 3000);
hard_task_def_arg(m2,(void *)"K");
p3 = task_create("3", edftask, &m2, NULL);
if (p3 == -1) {
perror("Could not create task edf ...");
sys_end();
}
 
cprintf("stars=%d", p2);
fineprg.tv_sec=140;
fineprg.tv_nsec=0;
kern_event_post(&fineprg,(void(*)(void *))sys_end, NULL);
group_activate(1);
}
 
int main(int argc, char **argv)
{
char c='t';
PI_mutexattr_t a;
PI_mutexattr_default(a);
 
//NOP_mutexattr_t a;
//NOP_mutexattr_default(a);
 
 
mutex_init(&s,&a);
 
clear();
 
cprintf("Hello, world!\nPress ESC to end the demo...\n");
 
create1();
 
do {
//c =keyb_getch(BLOCK);
// cprintf("[]");
} while (c != ESC);
 
cprintf("ESC pressed!");
 
sys_end();
 
return 0;
}
 
/advdemos/branches/advdemos/first/cbsstar.h
0,0 → 1,157
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
 
/*
------------
CVS : $Id: cbsstar.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
This file contains the budget support for the multiapplication
scheduling algorithm proposed in the framework of the FIRST Project
 
Title:
CBSSTAR
 
Task Models Accepted:
None!
 
Guest Models Accepted:
BUDGET_TASK_MODEL - A task that is attached to a budget
int b; --> the number of the budget which the task is attached to
 
Description:
This module schedule its tasks following the CBS scheme.
Every task is inserted using the guest calls.
The module defines a limited set of budgets that the application
can use. Every guest task will use a particular budget; FIFO
scheduling is used inside a budget to schedule more than one ready
task attached to the same budget.
 
The tasks are inserted in an EDF level (or similar) with a JOB_TASK_MODEL,
and the CBS level expects that the task is scheduled with the absolute
deadline passed in the model.
 
This module tries to implement a simplified version of the guest
task interface:
- To insert a guest task, use guest_create
- When a task is dispatched, use guest_dispatch
- When a task have to be suspended, you have to use:
-> preemption: use guest_epilogue
-> synchronization, end: use guest_end
Remember: no check is done on the budget number passed with the model!!!
 
Exceptions raised:
XUNVALID_TASK
This level doesn't support normal tasks, but just guest tasks.
When a task operation is called, an exception is raised.
 
Restrictions & special features:
- This level doesn't manage the main task.
- At init time we have to specify:
. guarantee check
(when all task are created the system will check that the task_set
will not use more than the available bandwidth)
- A function to return the used bandwidth of the level is provided.
 
- A function is provided to allocate a buffer.
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __CBSSTAR_H__
#define __CBSSTAR_H__
 
#include <kernel/kern.h>
 
//#include <ll/ll.h>
//#include <kernel/config.h>
//#include <sys/types.h>
//#include <kernel/types.h>
//#include <modules/codes.h>
 
/* -----------------------------------------------------------------------
BUDGET_TASK_MODEL: a model for guest tasks
----------------------------------------------------------------------- */
 
#define BUDGET_PCLASS 0x0600
typedef struct {
TASK_MODEL t;
int b;
} BUDGET_TASK_MODEL;
 
#define budget_task_default_model(m,buf) \
task_default_model((m).t, BUDGET_PCLASS), \
(m).b = (buf);
 
 
 
/* some constants for registering the Module in the right place */
#define CBSSTAR_LEVELNAME "CBSSTAR"
#define CBSSTAR_LEVEL_CODE 106
#define CBSSTAR_LEVEL_VERSION 1
 
 
 
 
/* Registration function:
int N Maximum number of budgets allocated for the applications
LEVEL master the level that must be used as master level for the
CBS tasks
*/
LEVEL CBSSTAR_register_level(int n, LEVEL master);
 
/* Allocates a budget to be used for an application.
Input parameters:
Q The budget
T The period of the budget
Return value:
0..N The ID of the budget
-1 no more free budgets
-2 The budgets allocated locally to this module have bandwidth > 1
-3 wrong LEVEL id
*/
int CBSSTAR_setbudget(LEVEL l, TIME Q, TIME T);
 
#endif
/advdemos/branches/advdemos/first/rmstar.c
0,0 → 1,640
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: rmstar.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "rmstar.h"
#include <ll/stdio.h>
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
/* for iqueues */
/* #include "iqueue.h" Now iqueues are the only queue type into the kernel */
 
/* for BUDGET_TASK_MODEL */
#include "cbsstar.h"
 
/*
* DEBUG stuffs begin
*/
 
//#define RMSTAR_DEBUG
 
#ifdef RMSTAR_DEBUG
 
static __inline__ fake_printf(char *fmt, ...) {}
 
#define rmstar_printf fake_printf
#define rmstar_printf2 fake_printf
#define rmstar_printf3 fake_printf
 
//#define rmstar_printf kern_printf
//#define rmstar_printf2 kern_printf
//#define rmstar_printf3 kern_printf
#endif
 
/*
* DEBUG stuffs end
*/
 
/* Status used in the level */
#define RMSTAR_READY MODULE_STATUS_BASE /* - Ready status */
#define RMSTAR_IDLE MODULE_STATUS_BASE+4 /* to wait the deadline */
 
/* flags */
#define RMSTAR_FLAG_NORAISEEXC 2
 
/* the level redefinition for the Earliest Deadline First level */
typedef struct {
level_des l; /* the standard level descriptor */
 
TIME period[MAX_PROC]; /* The task periods; the deadlines are
stored in the priority field */
int deadline_timer[MAX_PROC];
/* The task deadline timers */
 
struct timespec deadline_timespec[MAX_PROC];
 
int dline_miss[MAX_PROC]; /* Deadline miss counter */
int wcet_miss[MAX_PROC]; /* Wcet miss counter */
 
int nact[MAX_PROC]; /* Wcet miss counter */
 
int flag[MAX_PROC];
/* used to manage the JOB_TASK_MODEL and the
periodicity */
 
IQUEUE ready; /* the ready queue */
 
PID activated; /* the task that has been inserted into the
master module */
 
int budget;
 
int scheduling_level;
} RMSTAR_level_des;
 
static void RMSTAR_check_preemption(RMSTAR_level_des *lev)
{
PID first;
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:chk)");
#endif
 
if ((first = iq_query_first(&lev->ready)) != lev->activated) {
if (lev->activated != NIL)
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, lev->activated);
 
lev->activated = first;
 
if (first != NIL) {
BUDGET_TASK_MODEL b;
budget_task_default_model(b, lev->budget);
 
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, first, (TASK_MODEL *)&b);
}
}
}
 
static void RMSTAR_timer_deadline(void *par);
 
static void RMSTAR_internal_activate(RMSTAR_level_des *lev, PID p,
struct timespec *t)
{
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:iact)");
#endif
 
ADDUSEC2TIMESPEC(lev->period[p], t);
 
*iq_query_timespec(p, &lev->ready) = *t;
lev->deadline_timespec[p] = *t;
 
/* Insert task in the correct position */
proc_table[p].status = RMSTAR_READY;
iq_priority_insert(p,&lev->ready);
 
/* needed because when there is a wcet miss I disable CONTROL_CAP */
proc_table[p].control |= CONTROL_CAP;
 
/* check for preemption */
RMSTAR_check_preemption(lev);
}
 
static void RMSTAR_timer_deadline(void *par)
{
PID p = (PID) par;
RMSTAR_level_des *lev;
 
#ifdef RMSTAR_DEBUG
// rmstar_printf("(E:tdl ");
#endif
 
lev = (RMSTAR_level_des *)level_table[proc_table[p].task_level];
 
switch (proc_table[p].status) {
case RMSTAR_IDLE:
#ifdef RMSTAR_DEBUG
// rmstar_printf2("I%d",p);
#endif
/* set the request time */
RMSTAR_internal_activate(lev,p,iq_query_timespec(p, &lev->ready));
 
event_need_reschedule();
break;
 
default:
#ifdef RMSTAR_DEBUG
// rmstar_printf2("D%d",p);
#endif
/* else, a deadline miss occurred!!! */
lev->dline_miss[p]++;
 
/* the task is into another state */
lev->nact[p]++;
 
/* Set the deadline timer */
ADDUSEC2TIMESPEC(lev->period[p], &lev->deadline_timespec[p]);
}
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
RMSTAR_timer_deadline,
(void *)p);
 
#ifdef RMSTAR_DEBUG
// rmstar_printf(")");
#endif
}
 
static void RMSTAR_timer_guest_deadline(void *par)
{
PID p = (PID) par;
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:gdl)");
#endif
 
kern_raise(XDEADLINE_MISS,p);
}
 
static int RMSTAR_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
/* if the RMSTAR_task_create is called, then the pclass must be a
valid pclass. */
HARD_TASK_MODEL *h;
 
if (m->pclass != HARD_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
h = (HARD_TASK_MODEL *)m;
if (!h->wcet || !h->mit || h->periodicity != PERIODIC) return -1;
/* now we know that m is a valid model */
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:tcr)");
#endif
 
lev->period[p] = h->mit;
*iq_query_priority(p, &lev->ready) = h->mit;
 
lev->flag[p] = 0;
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
/* Enable wcet check */
proc_table[p].avail_time = h->wcet;
proc_table[p].wcet = h->wcet;
proc_table[p].control |= CONTROL_CAP;
 
return 0; /* OK, also if the task cannot be guaranteed... */
}
 
static void RMSTAR_public_dispatch(LEVEL l, PID p, int nostop)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:dis)");
 
rmstar_printf3("(%d %d)",
iq_query_timespec(p, &lev->ready)->tv_nsec/1000000,
schedule_time.tv_nsec/1000000);
#endif
 
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
}
 
static void RMSTAR_public_epilogue(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:epi ");
#endif
 
/* check if the wcet is finished... */
if (proc_table[p].avail_time <= 0 && proc_table[p].control&CONTROL_CAP) {
/* wcet finished: disable wcet event and count wcet miss */
#ifdef RMSTAR_DEBUG
rmstar_printf2("W%d",p);
#endif
proc_table[p].control &= ~CONTROL_CAP;
lev->wcet_miss[p]++;
}
#ifdef RMSTAR_DEBUG
rmstar_printf(")");
#endif
 
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
 
proc_table[p].status = RMSTAR_READY;
}
 
static void RMSTAR_public_activate(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
struct timespec t;
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:act)");
#endif
 
/* Test if we are trying to activate a non sleeping task */
/* save activation (only if needed... */
if (proc_table[p].status != SLEEP) {
/* a periodic task cannot be activated when it is already active */
kern_raise(XACTIVATION,p);
return;
}
 
kern_gettime(&t);
 
RMSTAR_internal_activate(lev,p, &t);
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
RMSTAR_timer_deadline,
(void *)p);
 
}
 
static void RMSTAR_public_unblock(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:ins)");
#endif
 
/* Insert task in the correct position */
proc_table[p].status = RMSTAR_READY;
iq_priority_insert(p,&lev->ready);
 
/* and check for preemption! */
RMSTAR_check_preemption(lev);
}
 
static void RMSTAR_public_block(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:ext)");
#endif
 
/* the task is blocked on a synchronization primitive. we have to
remove it from the master module -and- from the local queue! */
iq_extract(p,&lev->ready);
 
/* and finally, a preemption check! (it will also call guest_end) */
RMSTAR_check_preemption(lev);
}
 
static int RMSTAR_public_message(LEVEL l, PID p, void *m)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
struct timespec temp;
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:ecy ");
#endif
 
/* we call guest_end directly here because the same task may
be reinserted in the queue before calling the preemption check! */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p); lev->activated = NIL;
 
iq_extract(p,&lev->ready);
 
/* we reset the capacity counters... */
proc_table[p].avail_time = proc_table[p].wcet;
 
if (lev->nact[p] > 0) {
#ifdef RMSTAR_DEBUG
rmstar_printf2("E%d",p);
#endif
 
/* Pending activation: reactivate the thread!!! */
lev->nact[p]--;
 
/* see also RMSTAR_timer_deadline */
kern_gettime(&temp);
 
RMSTAR_internal_activate(lev,p,&temp);
 
/* check if the deadline has already expired */
temp = *iq_query_timespec(p, &lev->ready);
if (TIMESPEC_A_LT_B(&temp, &schedule_time)) {
/* count the deadline miss */
lev->dline_miss[p]++;
kern_event_delete(lev->deadline_timer[p]);
}
 
}
else {
#ifdef RMSTAR_DEBUG
rmstar_printf("e%d",p);
#endif
 
/* the task has terminated his job before it consume the wcet. All OK! */
proc_table[p].status = RMSTAR_IDLE;
 
/* and finally, a preemption check! */
RMSTAR_check_preemption(lev);
 
/* when the deadline timer fire, it recognize the situation and set
correctly all the stuffs (like reactivation, etc... ) */
}
#ifdef RMSTAR_DEBUG
rmstar_printf(")");
#endif
 
jet_update_endcycle(); /* Update the Jet data... */
 
return 0;
}
 
static void RMSTAR_public_end(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
rmstar_printf("(E:end)");
#endif
 
iq_extract(p,&lev->ready);
 
/* we finally put the task in the ready queue */
proc_table[p].status = FREE;
iq_insertfirst(p,&freedesc);
if (lev->deadline_timer[p] != -1) {
kern_event_delete(lev->deadline_timer[p]);
}
 
/* and finally, a preemption check! (it will also call guest_end) */
RMSTAR_check_preemption(lev);
}
 
 
/* Guest Functions
These functions manages a JOB_TASK_MODEL, that is used to put
a guest task in the RMSTAR ready queue. */
 
static void RMSTAR_private_insert(LEVEL l, PID p, TASK_MODEL *m)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
JOB_TASK_MODEL *job;
 
if (m->pclass != JOB_PCLASS || (m->level != 0 && m->level != l) ) {
kern_raise(XINVALID_TASK, p);
return;
}
 
job = (JOB_TASK_MODEL *)m;
 
*iq_query_timespec(p, &lev->ready) = job->deadline;
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
if (job->noraiseexc)
lev->flag[p] = RMSTAR_FLAG_NORAISEEXC;
else {
lev->flag[p] = 0;
lev->deadline_timer[p] = kern_event_post(iq_query_timespec(p, &lev->ready),
RMSTAR_timer_guest_deadline,
(void *)p);
}
 
lev->period[p] = job->period;
*iq_query_priority(p, &lev->ready) = job->period;
 
/* there is no bandwidth guarantee at this level, it is performed
by the level that inserts guest tasks... */
 
/* Insert task in the correct position */
iq_priority_insert(p,&lev->ready);
proc_table[p].status = RMSTAR_READY;
 
/* check for preemption */
RMSTAR_check_preemption(lev);
}
 
static void RMSTAR_private_dispatch(LEVEL l, PID p, int nostop)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
}
 
static void RMSTAR_private_epilogue(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
/* the task has been preempted. it returns into the ready queue... */
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
 
proc_table[p].status = RMSTAR_READY;
}
 
static void RMSTAR_private_extract(LEVEL l, PID p)
{
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
#ifdef RMSTAR_DEBUG
//kern_printf("RMSTAR_guest_end: dline timer %d\n",lev->deadline_timer[p]);
#endif
 
iq_extract(p, &lev->ready);
 
/* we remove the deadline timer, because the slice is finished */
if (lev->deadline_timer[p] != NIL) {
#ifdef RMSTAR_DEBUG
// kern_printf("RMSTAR_guest_end: dline timer %d\n",lev->deadline_timer[p]);
#endif
kern_event_delete(lev->deadline_timer[p]);
lev->deadline_timer[p] = NIL;
}
 
/* and finally, a preemption check! (it will also call guest_end() */
RMSTAR_check_preemption(lev);
}
 
/* Registration functions */
 
/* Registration function:
int flags the init flags ... see RMSTAR.h */
LEVEL RMSTAR_register_level(int budget, int master)
{
LEVEL l; /* the level that we register */
RMSTAR_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
#ifdef RMSTAR_DEBUG
printk("RMSTAR_register_level\n");
#endif
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(RMSTAR_level_des));
 
lev = (RMSTAR_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.private_insert = RMSTAR_private_insert;
lev->l.private_extract = RMSTAR_private_extract;
lev->l.private_dispatch = RMSTAR_private_dispatch;
lev->l.private_epilogue = RMSTAR_private_epilogue;
 
lev->l.public_guarantee = NULL;
lev->l.public_create = RMSTAR_public_create;
lev->l.public_end = RMSTAR_public_end;
lev->l.public_dispatch = RMSTAR_public_dispatch;
lev->l.public_epilogue = RMSTAR_public_epilogue;
lev->l.public_activate = RMSTAR_public_activate;
lev->l.public_unblock = RMSTAR_public_unblock;
lev->l.public_block = RMSTAR_public_block;
lev->l.public_message = RMSTAR_public_message;
 
/* fill the RMSTAR descriptor part */
for(i=0; i<MAX_PROC; i++) {
lev->period[i] = 0;
lev->deadline_timer[i] = -1;
lev->flag[i] = 0;
lev->dline_miss[i] = 0;
lev->wcet_miss[i] = 0;
lev->nact[i] = 0;
}
 
iq_init(&lev->ready, NULL, 0);
lev->activated = NIL;
 
lev->budget = budget;
lev->scheduling_level = master;
 
return l;
}
 
int RMSTAR_get_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
return lev->dline_miss[p];
}
 
int RMSTAR_get_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
return lev->wcet_miss[p];
}
 
int RMSTAR_get_nact(PID p)
{
LEVEL l = proc_table[p].task_level;
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
return lev->nact[p];
}
 
int RMSTAR_reset_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
lev->dline_miss[p] = 0;
return 0;
}
 
int RMSTAR_reset_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
RMSTAR_level_des *lev = (RMSTAR_level_des *)(level_table[l]);
 
lev->wcet_miss[p] = 0;
return 0;
}
 
/advdemos/branches/advdemos/first/testiq.c
0,0 → 1,260
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: testiq.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
The purpose of this test is to show that two budgets with different
period and budgets schedules correctly.
2 never ending tasks are involved
 
This test cannot compile because of the fact that QUEUE and QQUEUE
types does not exist anymore!
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "cbsstar.h"
#include "edfstar.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
clear();
 
EDF_register_level(EDF_ENABLE_ALL);
 
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
//keyb_def_ctrlC(kparms, NULL);
//keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
 
#include <kernel/kern.h>
#include <drivers/keyb.h>
#include "iqueue.h"
 
sem_t s;
 
PID p2,p3,p4;
 
void *star(void *arg)
{
int j;
TIME last[5];
 
QUEUE i = NIL;
IQUEUE ii;
 
q_timespec_insert(p2,&i);
q_timespec_insert(p3,&i);
 
iq_init(&ii,NULL,0);
*iq_query_timespec(p2,&ii) = proc_table[p2].timespec_priority;
*iq_query_timespec(p3,&ii) = proc_table[p3].timespec_priority;
*iq_query_timespec(p4,&ii) = proc_table[p4].timespec_priority;
iq_timespec_insert(p2,&ii);
iq_timespec_insert(p3,&ii);
 
cprintf("p2=%ld.%ld\n",proc_table[p2].timespec_priority.tv_sec,proc_table[p2].timespec_priority.tv_nsec/1000);
cprintf("p3=%ld.%ld\n",proc_table[p3].timespec_priority.tv_sec,proc_table[p3].timespec_priority.tv_nsec/1000);
cprintf("p4=%ld.%ld\n",proc_table[p4].timespec_priority.tv_sec,proc_table[p4].timespec_priority.tv_nsec/1000);
 
task_endcycle();
 
for (j=0; j<200000; j++) {
q_timespec_insert(p4,&i);
q_extract(p4,&i);
}
 
 
task_endcycle();
 
for (j=0; j<200000; j++) {
iq_timespec_insert(p4,&ii);
iq_extract(p4,&ii);
}
 
task_endcycle();
 
jet_gettable(exec_shadow, &last[0], 3);
 
cprintf("\ninit=%d queue=%d iqueue=%d\n",
(int)last[0], (int)last[1], (int)last[2]);
 
sys_end();
return NULL;
}
 
void *fake(void *arg)
{
cputs("#");
task_endcycle();
 
return NULL;
}
 
 
void create1()
{
HARD_TASK_MODEL m1;
PID p1a;
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 500000);
hard_task_def_group(m1,1);
hard_task_def_periodic(m1);
hard_task_def_mit(m1,1000000);
hard_task_def_ctrl_jet(m1);
p1a = task_create("a", star, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_default_model(m1);
hard_task_def_wcet(m1, 5000);
hard_task_def_aperiodic(m1);
hard_task_def_group(m1,1);
 
hard_task_def_mit(m1,100000);
p2 = task_create("a", fake, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_def_mit(m1,100001);
p3 = task_create("a", fake, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
hard_task_def_mit(m1,100002);
p4 = task_create("a", fake, &m1, NULL);
if (p1a == -1) {
perror("Could not create task a ...");
sys_end();
}
 
group_activate(1);
}
 
void endfun(KEY_EVT *k)
{
cprintf("ESC pressed!");
 
sys_end();
}
 
int main(int argc, char **argv)
{
KEY_EVT k;
 
sem_init(&s,0,1);
 
k.flag = 0;
k.scan = KEY_ESC;
k.ascii = 27;
keyb_hook(k,endfun);
 
create1();
 
return 0;
}
 
/advdemos/branches/advdemos/first/rmstar.h
0,0 → 1,128
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: rmstar.h,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
Title:
RMSTAR
 
Task Models Accepted:
HARD_TASK_MODEL - Hard Tasks (only Periodic)
wcet field and mit field must be != 0. They are used to set the wcet
and period of the tasks.
periodicity field can be only PERIODIC
drel field is ignored
Guest Models Accepted:
JOB_TASK_MODEL - a single guest task activation
Identified by an absolute deadline and a period.
period field is ignored
 
Description:
 
This module schedule his tasks following the classic RM
scheme.
 
Note: This module is derived from the EDFSTAR Scheduling Module. I
have just changed RM in EDF and iq_timespec_insert with
iq_priority_insert...
 
Exceptions raised:
XUNVALID_GUEST XUNVALID_TASK
some primitives are not implemented:
task_sleep, task_delay, guest_endcycle, guest_sleep, guest_delay
 
XACTIVATION
If a task is actiated through task_activate or guest_activate more than
one time
Restrictions & special features:
see edfstar.h
 
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __RMSTAR_H__
#define __RMSTAR_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
 
 
 
/* flags... */
#define RMSTAR_ENABLE_GUARANTEE 1 /* Task Guarantee enabled */
#define RMSTAR_ENABLE_ALL 1
 
#define RMSTAR_FAILED_GUARANTEE 8 /* used in the module, unsettabl
in RM_register_level... */
 
 
 
#define RMSTAR_LEVELNAME "RMSTAR base"
#define RMSTAR_LEVEL_CODE 166
#define RMSTAR_LEVEL_VERSION 1
 
 
/* Registration function:
int budget The budget used by this module (see CBSSTAR.h)
int master The master module used by RMSTAR
*/
LEVEL RMSTAR_register_level(int budget, int master);
 
/* returns respectively the number of dline, wcet or nact; -1 if error */
int RMSTAR_get_dline_miss(PID p);
int RMSTAR_get_wcet_miss(PID p);
int RMSTAR_get_nact(PID p);
 
/* resets respectively the number of dline, wcet miss; -1 if error */
int RMSTAR_reset_dline_miss(PID p);
int RMSTAR_reset_wcet_miss(PID p);
 
#endif
 
/advdemos/branches/advdemos/first/edfstar.c
0,0 → 1,657
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: edfstar.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "edfstar.h"
#include <ll/stdio.h>
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
/* for iqueues */
/* #include "iqueue.h" Now iqueues are the only queue type available
into the kernel */
#include <kernel/iqueue.h>
 
/* for BUDGET_TASK_MODEL */
#include "cbsstar.h"
 
/*
* DEBUG stuffs begin
*/
 
//#define EDFSTAR_DEBUG
 
#ifdef EDFSTAR_DEBUF
 
static __inline__ fake_printf(char *fmt, ...) {}
 
#define edfstar_printf fake_printf
#define edfstar_printf2 fake_printf
#define edfstar_printf3 fake_printf
 
//#define edfstar_printf kern_printf
//#define edfstar_printf2 kern_printf
//#define edfstar_printf3 kern_printf
#endif
 
/*
* DEBUG stuffs end
*/
 
/* Status used in the level */
#define EDFSTAR_READY MODULE_STATUS_BASE /* - Ready status */
#define EDFSTAR_IDLE MODULE_STATUS_BASE+4 /* to wait the deadline */
 
/* flags */
#define EDFSTAR_FLAG_NORAISEEXC 2
 
/* the level redefinition for the Earliest Deadline First level */
typedef struct {
level_des l; /* the standard level descriptor */
 
TIME period[MAX_PROC]; /* The task periods; the deadlines are
stored in the priority field */
int deadline_timer[MAX_PROC];
/* The task deadline timers */
 
struct timespec deadline_timespec[MAX_PROC];
 
int dline_miss[MAX_PROC]; /* Deadline miss counter */
int wcet_miss[MAX_PROC]; /* Wcet miss counter */
 
int nact[MAX_PROC]; /* Wcet miss counter */
 
int flag[MAX_PROC];
/* used to manage the JOB_TASK_MODEL and the
periodicity */
 
IQUEUE ready; /* the ready queue */
 
PID activated; /* the task that has been inserted into the
master module */
 
int budget;
 
int scheduling_level;
} EDFSTAR_level_des;
 
static void EDFSTAR_check_preemption(EDFSTAR_level_des *lev)
{
PID first;
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:chk)");
#endif
 
if ((first = iq_query_first(&lev->ready)) != lev->activated) {
if (lev->activated != NIL)
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, lev->activated);
 
lev->activated = first;
 
if (first != NIL) {
BUDGET_TASK_MODEL b;
budget_task_default_model(b, lev->budget);
 
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, first, (TASK_MODEL *)&b);
}
}
}
 
static void EDFSTAR_timer_deadline(void *par);
 
static void EDFSTAR_internal_activate(EDFSTAR_level_des *lev, PID p,
struct timespec *t)
{
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:iact)");
#endif
 
ADDUSEC2TIMESPEC(lev->period[p], t);
 
*iq_query_timespec(p, &lev->ready) = *t;
lev->deadline_timespec[p] = *t;
 
/* Insert task in the correct position */
proc_table[p].status = EDFSTAR_READY;
iq_timespec_insert(p,&lev->ready);
 
/* needed because when there is a wcet miss I disable CONTROL_CAP */
proc_table[p].control |= CONTROL_CAP;
 
/* check for preemption */
EDFSTAR_check_preemption(lev);
}
 
static void EDFSTAR_timer_deadline(void *par)
{
PID p = (PID) par;
EDFSTAR_level_des *lev;
 
#ifdef EDFSTAR_DEBUG
// edfstar_printf("(E:tdl ");
#endif
 
lev = (EDFSTAR_level_des *)level_table[proc_table[p].task_level];
 
switch (proc_table[p].status) {
case EDFSTAR_IDLE:
#ifdef EDFSTAR_DEBUG
// edfstar_printf2("I%d",p);
#endif
/* set the request time */
EDFSTAR_internal_activate(lev,p,iq_query_timespec(p, &lev->ready));
 
event_need_reschedule();
break;
 
default:
#ifdef EDFSTAR_DEBUG
// edfstar_printf2("D%d",p);
#endif
/* else, a deadline miss occurred!!! */
lev->dline_miss[p]++;
 
/* the task is into another state */
lev->nact[p]++;
 
/* Set the deadline timer */
ADDUSEC2TIMESPEC(lev->period[p], &lev->deadline_timespec[p]);
}
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
EDFSTAR_timer_deadline,
(void *)p);
 
#ifdef EDFSTAR_DEBUG
// edfstar_printf(")");
#endif
}
 
static void EDFSTAR_timer_guest_deadline(void *par)
{
PID p = (PID) par;
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:gdl)");
#endif
 
kern_raise(XDEADLINE_MISS,p);
}
 
static int EDFSTAR_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
/* if the EDFSTAR_task_create is called, then the pclass must be a
valid pclass. */
HARD_TASK_MODEL *h;
 
if (m->pclass != HARD_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
h = (HARD_TASK_MODEL *)m;
if (!h->wcet || !h->mit || h->periodicity != PERIODIC) return -1;
/* now we know that m is a valid model */
 
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:tcr)");
#endif
 
lev->period[p] = h->mit;
 
lev->flag[p] = 0;
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
/* Enable wcet check */
proc_table[p].avail_time = h->wcet;
proc_table[p].wcet = h->wcet;
proc_table[p].control |= CONTROL_CAP;
 
return 0; /* OK, also if the task cannot be guaranteed... */
}
 
static int EDFSTAR_public_eligible(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf2("(E:eli)");
#endif
 
return level_table[ lev->scheduling_level ]->
private_eligible(lev->scheduling_level,p);
}
 
static void EDFSTAR_public_dispatch(LEVEL l, PID p, int nostop)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:dis)");
 
edfstar_printf3("(%d %d)",
iq_query_timespec(p, &lev->ready)->tv_nsec/1000000,
schedule_time.tv_nsec/1000000);
#endif
 
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
}
 
static void EDFSTAR_public_epilogue(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:epi ");
#endif
 
/* check if the wcet is finished... */
if (proc_table[p].avail_time <= 0 && proc_table[p].control&CONTROL_CAP) {
/* wcet finished: disable wcet event and count wcet miss */
#ifdef EDFSTAR_DEBUG
edfstar_printf2("W%d",p);
#endif
proc_table[p].control &= ~CONTROL_CAP;
lev->wcet_miss[p]++;
}
#ifdef EDFSTAR_DEBUG
edfstar_printf(")");
#endif
 
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
 
proc_table[p].status = EDFSTAR_READY;
}
 
static void EDFSTAR_public_activate(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
struct timespec t;
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:act)");
#endif
 
/* Test if we are trying to activate a non sleeping task */
/* save activation (only if needed... */
if (proc_table[p].status != SLEEP) {
/* a periodic task cannot be activated when it is already active */
kern_raise(XACTIVATION,p);
return;
}
 
kern_gettime(&t);
 
EDFSTAR_internal_activate(lev,p, &t);
 
/* Set the deadline timer */
lev->deadline_timer[p] = kern_event_post(&lev->deadline_timespec[p],
EDFSTAR_timer_deadline,
(void *)p);
 
}
 
static void EDFSTAR_public_unblock(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:ins)");
#endif
 
/* Insert task in the correct position */
proc_table[p].status = EDFSTAR_READY;
iq_timespec_insert(p,&lev->ready);
 
/* and check for preemption! */
EDFSTAR_check_preemption(lev);
}
 
static void EDFSTAR_public_block(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:ext)");
#endif
 
/* the task is blocked on a synchronization primitive. we have to
remove it from the master module -and- from the local queue! */
iq_extract(p,&lev->ready);
 
/* and finally, a preemption check! (it will also call guest_end) */
EDFSTAR_check_preemption(lev);
}
 
static int EDFSTAR_public_message(LEVEL l, PID p, void *m)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
struct timespec temp;
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:ecy ");
#endif
 
/* we call guest_end directly here because the same task may
be reinserted in the queue before calling the preemption check! */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p);
lev->activated = NIL;
 
iq_extract(p,&lev->ready);
 
/* we reset the capacity counters... */
proc_table[p].avail_time = proc_table[p].wcet;
 
if (lev->nact[p] > 0) {
#ifdef EDFSTAR_DEBUG
edfstar_printf2("E%d",p);
#endif
 
/* Pending activation: reactivate the thread!!! */
lev->nact[p]--;
 
/* see also EDFSTAR_timer_deadline */
kern_gettime(&temp);
 
EDFSTAR_internal_activate(lev,p, &temp);
 
/* check if the deadline has already expired */
temp = *iq_query_timespec(p, &lev->ready);
if (TIMESPEC_A_LT_B(&temp, &schedule_time)) {
/* count the deadline miss */
lev->dline_miss[p]++;
kern_event_delete(lev->deadline_timer[p]);
}
 
}
else {
#ifdef EDFSTAR_DEBUG
edfstar_printf("e%d",p);
#endif
 
/* the task has terminated his job before it consume the wcet. All OK! */
proc_table[p].status = EDFSTAR_IDLE;
 
/* and finally, a preemption check! */
EDFSTAR_check_preemption(lev);
 
/* when the deadline timer fire, it recognize the situation and set
correctly all the stuffs (like reactivation, etc... ) */
}
#ifdef EDFSTAR_DEBUG
edfstar_printf(")");
#endif
 
jet_update_endcycle(); /* Update the Jet data... */
 
return 0;
}
 
static void EDFSTAR_public_end(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
edfstar_printf("(E:end)");
#endif
 
iq_extract(p,&lev->ready);
 
/* we finally put the task in the ready queue */
proc_table[p].status = FREE;
iq_insertfirst(p,&freedesc);
if (lev->deadline_timer[p] != -1) {
kern_event_delete(lev->deadline_timer[p]);
}
 
/* and finally, a preemption check! (it will also call guest_end) */
EDFSTAR_check_preemption(lev);
}
 
/* Guest Functions
These functions manages a JOB_TASK_MODEL, that is used to put
a guest task in the EDFSTAR ready queue. */
 
static void EDFSTAR_private_insert(LEVEL l, PID p, TASK_MODEL *m)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
JOB_TASK_MODEL *job;
 
if (m->pclass != JOB_PCLASS || (m->level != 0 && m->level != l) ) {
kern_raise(XINVALID_TASK, p);
return;
}
 
job = (JOB_TASK_MODEL *)m;
 
/* if the EDFSTAR_guest_create is called, then the pclass must be a
valid pclass. */
 
*iq_query_timespec(p, &lev->ready) = job->deadline;
lev->deadline_timer[p] = -1;
lev->dline_miss[p] = 0;
lev->wcet_miss[p] = 0;
lev->nact[p] = 0;
 
if (job->noraiseexc)
lev->flag[p] = EDFSTAR_FLAG_NORAISEEXC;
else {
lev->flag[p] = 0;
lev->deadline_timer[p] = kern_event_post(iq_query_timespec(p, &lev->ready),
EDFSTAR_timer_guest_deadline,
(void *)p);
}
 
lev->period[p] = job->period;
 
/* Insert task in the correct position */
iq_timespec_insert(p,&lev->ready);
proc_table[p].status = EDFSTAR_READY;
 
/* check for preemption */
EDFSTAR_check_preemption(lev);
 
/* there is no bandwidth guarantee at this level, it is performed
by the level that inserts guest tasks... */
}
 
static void EDFSTAR_private_dispatch(LEVEL l, PID p, int nostop)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
}
 
static void EDFSTAR_private_epilogue(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
/* the task has been preempted. it returns into the ready queue... */
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
 
proc_table[p].status = EDFSTAR_READY;
}
 
static void EDFSTAR_private_extract(LEVEL l, PID p)
{
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
#ifdef EDFSTAR_DEBUG
//kern_printf("EDFSTAR_guest_end: dline timer %d\n",lev->deadline_timer[p]);
#endif
 
iq_extract(p, &lev->ready);
 
/* we remove the deadline timer, because the slice is finished */
if (lev->deadline_timer[p] != NIL) {
#ifdef EDFSTAR_DEBUG
// kern_printf("EDFSTAR_guest_end: dline timer %d\n",lev->deadline_timer[p]);
#endif
kern_event_delete(lev->deadline_timer[p]);
lev->deadline_timer[p] = NIL;
}
 
/* and finally, a preemption check! (it will also call guest_end() */
EDFSTAR_check_preemption(lev);
}
 
/* Registration functions */
 
/* Registration function:
int flags the init flags ... see EDFSTAR.h */
LEVEL EDFSTAR_register_level(int budget, int master)
{
LEVEL l; /* the level that we register */
EDFSTAR_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
#ifdef EDFSTAR_DEBUG
printk("EDFSTAR_register_level\n");
#endif
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(EDFSTAR_level_des));
 
lev = (EDFSTAR_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.private_insert = EDFSTAR_private_insert;
lev->l.private_extract = EDFSTAR_private_extract;
lev->l.private_dispatch = EDFSTAR_private_dispatch;
lev->l.private_epilogue = EDFSTAR_private_epilogue;
 
lev->l.public_guarantee = NULL;
lev->l.public_eligible = EDFSTAR_public_eligible;
lev->l.public_create = EDFSTAR_public_create;
lev->l.public_end = EDFSTAR_public_end;
lev->l.public_dispatch = EDFSTAR_public_dispatch;
lev->l.public_epilogue = EDFSTAR_public_epilogue;
lev->l.public_activate = EDFSTAR_public_activate;
lev->l.public_unblock = EDFSTAR_public_unblock;
lev->l.public_block = EDFSTAR_public_block;
lev->l.public_message = EDFSTAR_public_message;
 
/* fill the EDFSTAR descriptor part */
for(i=0; i<MAX_PROC; i++) {
lev->period[i] = 0;
lev->deadline_timer[i] = -1;
lev->flag[i] = 0;
lev->dline_miss[i] = 0;
lev->wcet_miss[i] = 0;
lev->nact[i] = 0;
}
 
iq_init(&lev->ready, NULL, IQUEUE_NO_PRIORITY);
lev->activated = NIL;
 
lev->budget = budget;
lev->scheduling_level = master;
 
return l;
}
 
int EDFSTAR_get_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
return lev->dline_miss[p];
}
 
int EDFSTAR_get_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
return lev->wcet_miss[p];
}
 
int EDFSTAR_get_nact(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
return lev->nact[p];
}
 
int EDFSTAR_reset_dline_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
lev->dline_miss[p] = 0;
return 0;
}
 
int EDFSTAR_reset_wcet_miss(PID p)
{
LEVEL l = proc_table[p].task_level;
EDFSTAR_level_des *lev = (EDFSTAR_level_des *)(level_table[l]);
 
lev->wcet_miss[p] = 0;
return 0;
}
 
/advdemos/branches/advdemos/first/posixstar.c
0,0 → 1,541
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Trimarchi Michael <trimarchi@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: posixstar.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
This file contains the scheduling module compatible with POSIX
specifications
 
Read posixstar.h for further details.
 
RR tasks have the CONTROL_CAP bit set
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR2ANTY; without even the implied waRR2anty 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
*
*/
 
 
#include <ll/stdio.h>
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
#include "posixstar.h"
#include "cbsstar.h"
//#define POSIXSTAR_DEBUG
/*+ Status used in the level +*/
#define POSIXSTAR_READY MODULE_STATUS_BASE
 
/*+ the level redefinition for the Round Robin level +*/
typedef struct {
level_des l; /*+ the standard level descriptor +*/
 
int nact[MAX_PROC]; /*+ number of pending activations +*/
int priority[MAX_PROC]; /*+ priority of each task +*/
 
IQUEUE *ready; /*+ the ready queue array +*/
 
int slice; /*+ the level's time slice +*/
 
// the multiboot is not usefull for this module
// struct multiboot_info *multiboot; /*+ used if the level have to insert
// the main task +*/
int maxpriority; /*+ the priority are from 0 to maxpriority
(i.e 0 to 31) +*/
 
int yielding; /*+ equal to 1 when a sched_yield is called +*/
 
int budget;
 
PID activated;
int scheduling_level;
} POSIXSTAR_level_des;
 
/* the private scheduler choice a task and insert in cbsstar module */
/* This is not efficient but very fair :-)
The need of all this stuff is because if a task execute a long time
due to (shadow!) priority inheritance, then the task shall go to the
tail of the queue many times... */
 
static void POSIXSTAR_private_scheduler(POSIXSTAR_level_des * lev)
{
/* the old posix scheduler select the private job for CBS */
PID p=NIL;
 
int prio;
 
prio = lev->maxpriority;
 
for (;;) {
p = iq_query_first(&lev->ready[prio]);
if (p == NIL) {
if (prio) {
prio--;
continue;
}
else {
p=NIL;
break;
}
}
//if (p != NIL && (proc_table[p].control & CONTROL_CAP))
// kern_printf("CC SET %d",p);
//kern_printf("task %d", p);
 
if ((proc_table[p].control & CONTROL_CAP) &&
(proc_table[p].avail_time <= 0)) {
if (proc_table[p].avail_time<=0)
proc_table[p].avail_time += proc_table[p].wcet;
//kern_printf("RR policy");
iq_extract(p,&lev->ready[prio]);
iq_insertlast(p,&lev->ready[prio]);
}
else {
break;
}
}
 
if (p!=lev->activated) {
if (lev->activated != NIL ) {
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, lev->activated);
//kern_printf("CBS ext %d",p);
}
lev->activated = p;
if (p != NIL) {
BUDGET_TASK_MODEL b;
budget_task_default_model(b, lev->budget);
//kern_printf("(Act %d",p);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&b);
}
}
}
 
static int POSIXSTAR_public_eligible(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
if (p==lev->activated) {
//kern_printf("eli %d", p);
 
return level_table[ lev->scheduling_level ]->
private_eligible(lev->scheduling_level,p);
}
return 0;
}
 
static int POSIXSTAR_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
NRT_TASK_MODEL *nrt;
 
if (m->pclass != NRT_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
 
nrt = (NRT_TASK_MODEL *)m;
 
/* the task state is set at SLEEP by the general task_create */
 
/* I used the wcet field because using wcet can account if a task
consume more than the timeslice... */
 
if (nrt->inherit == NRT_INHERIT_SCHED &&
proc_table[exec_shadow].task_level == l) {
/* We inherit the scheduling properties if the scheduling level
*is* the same */
lev->priority[p] = lev->priority[exec_shadow];
proc_table[p].avail_time = proc_table[exec_shadow].avail_time;
proc_table[p].wcet = proc_table[exec_shadow].wcet;
 
proc_table[p].control = (proc_table[p].control & ~CONTROL_CAP) |
(proc_table[exec_shadow].control & CONTROL_CAP);
lev->nact[p] = (lev->nact[exec_shadow] == -1) ? -1 : 0;
}
else {
if (nrt->weight<=lev->maxpriority)
lev->priority[p] = nrt->weight;
else lev->priority[p]=lev->maxpriority;
if (nrt->slice) {
proc_table[p].avail_time = nrt->slice;
proc_table[p].wcet = nrt->slice;
}
else {
proc_table[p].avail_time = lev->slice;
proc_table[p].wcet = lev->slice;
}
if (nrt->policy == NRT_RR_POLICY) {
proc_table[p].control |= CONTROL_CAP;
//kern_printf("CCAP set:%d",p);
 
}
if (nrt->arrivals == SAVE_ARRIVALS)
lev->nact[p] = 0;
else
lev->nact[p] = -1;
}
 
return 0; /* OK */
}
 
static void POSIXSTAR_public_dispatch(LEVEL l, PID p, int nostop)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
//#ifdef POSIXSTAR_DEBUG
 
//#endif
/* the task state is set EXE by the scheduler()
we extract the task from the ready queue
NB: we can't assume that p is the first task in the queue!!! */
//iq_extract(p, &lev->ready[lev->priority[p]]);
//if (!nostop) {
//kern_printf("PDisp:%d(%d)",p, lev->activated);
if (p==lev->activated)
level_table[lev->scheduling_level]->private_dispatch(lev->scheduling_level, p, nostop);
//} else
// kern_printf("PDisp:%d(%d)",p, lev->activated);
}
 
static void POSIXSTAR_public_epilogue(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
//#ifdef POSIXSTAR_DEBUG
//kern_printf("PEpic:%d",p);
//#endif
if (p==lev->activated) {
if (lev->yielding) {
lev->yielding = 0;
iq_extract(p,&lev->ready[lev->priority[p]]);
iq_insertlast(p,&lev->ready[lev->priority[p]]);
}
/* check if the slice is finished and insert the task in the coPOSIXect
qqueue position */
else if (proc_table[p].control & CONTROL_CAP &&
proc_table[p].avail_time <= 0) {
//proc_table[p].avail_time += proc_table[p].wcet;
//kern_printf("avail_time %d", proc_table[p].avail_time);
iq_extract(p,&lev->ready[lev->priority[p]]);
iq_insertlast(p,&lev->ready[lev->priority[p]]);
//level_table[lev->scheduling_level]->private_extract(lev->scheduling_level,p);
//lev->activated=NIL;
POSIXSTAR_private_scheduler(lev);
if (p==lev->activated)
level_table[lev->scheduling_level]->private_epilogue(lev->scheduling_level,p);
}
else {
//iq_insertfirst(p,&lev->ready[lev->priority[p]]);
level_table[lev->scheduling_level]->private_epilogue(lev->scheduling_level,p);
}
proc_table[p].status = POSIXSTAR_READY;
}
}
 
static void POSIXSTAR_internal_activate(POSIXSTAR_level_des *lev, PID p)
{
 
/* Insert task in the correct position */
proc_table[p].status = POSIXSTAR_READY;
iq_insertlast(p,&lev->ready[lev->priority[p]]);
 
}
 
static void POSIXSTAR_public_activate(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
/* Test if we are trying to activate a non sleeping task */
/* save activation (only if needed...) */
if (proc_table[p].status != SLEEP) {
if (lev->nact[p] != -1)
lev->nact[p]++;
return;
}
#ifdef POSIXSTAR_DEBUG
kern_printf("PA:%d",p);
#endif
POSIXSTAR_internal_activate(lev, p);
POSIXSTAR_private_scheduler(lev);
 
}
 
 
static void POSIXSTAR_public_unblock(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
/* Similar to POSIX_task_activate, but we don't check in what state
the task is */
 
/* Insert task in the coPOSIXect position */
//kern_printf("PU:%d", p);
proc_table[p].status = POSIXSTAR_READY;
iq_insertlast(p,&lev->ready[lev->priority[p]]);
POSIXSTAR_private_scheduler(lev);
}
 
static void POSIXSTAR_public_block(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
/* Extract the running task from the level
. we have already extract it from the ready queue at the dispatch time.
. the capacity event have to be removed by the generic kernel
. the wcet don't need modification...
. the state of the task is set by the calling function
 
So, we do nothing!!!
*/
 
//#ifdef POSIXSTAR_DEBUG
//kern_printf("PB:%d", p);
//#endif
iq_extract(p,&lev->ready[lev->priority[p]]);
POSIXSTAR_private_scheduler(lev);
}
 
static int POSIXSTAR_public_message(LEVEL l, PID p, void *m)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
if (lev->nact[p] > 0) {
/* continue!!!! */
lev->nact[p]--;
iq_extract(p,&lev->ready[lev->priority[p]]);
iq_insertfirst(p,&lev->ready[lev->priority[p]]);
proc_table[p].status = POSIXSTAR_READY;
}
else {
proc_table[p].status = SLEEP;
 
}
//#ifdef POSIXSTAR_DEBUG
kern_printf("PM:%d",p);
//#endif
POSIXSTAR_private_scheduler(lev);
return 0;
}
 
static void POSIXSTAR_public_end(LEVEL l, PID p)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
#ifdef POSIXSTAR_DEBUG
kern_printf("PEnd:%d", p);
#endif
lev->nact[p] = -1;
 
/* then, we insert the task in the free queue */
proc_table[p].status = FREE;
iq_priority_insert(p,NULL);
POSIXSTAR_private_scheduler(lev);
}
 
/* Registration functions */
 
/*+ Registration function:
TIME slice the slice for the Round Robin queue
struct multiboot_info *mb used if createmain specified +*/
LEVEL POSIXSTAR_register_level(int budget, int master, TIME slice,
int prioritylevels)
{
LEVEL l; /* the level that we register */
POSIXSTAR_level_des *lev; /* for readableness only */
PID i; /* a counter */
int x; /* a counter */
 
printk("POSIXSTAR_register_level\n");
 
l = level_alloc_descriptor(sizeof(POSIXSTAR_level_des));
 
lev = (POSIXSTAR_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
/*
lev->l.private_insert = NULL;
lev->l.private_extract = NULL;
lev->l.private_dispatch = NULL;
lev->l.private_epilogue = NULL;
*/
 
//lev->l.public_scheduler = NULL;
lev->l.public_create = POSIXSTAR_public_create;
lev->l.public_end = POSIXSTAR_public_end;
lev->l.public_dispatch = POSIXSTAR_public_dispatch;
lev->l.public_epilogue = POSIXSTAR_public_epilogue;
lev->l.public_activate = POSIXSTAR_public_activate;
lev->l.public_unblock = POSIXSTAR_public_unblock;
lev->l.public_block = POSIXSTAR_public_block;
lev->l.public_message = POSIXSTAR_public_message;
lev->l.public_eligible = POSIXSTAR_public_eligible;
 
/* fill the POSIX descriptor part */
for (i = 0; i < MAX_PROC; i++)
lev->nact[i] = -1;
 
lev->maxpriority = prioritylevels -1;
 
lev->ready = (IQUEUE *)kern_alloc(sizeof(IQUEUE) * prioritylevels);
 
for (x = 0; x < prioritylevels; x++)
iq_init(&lev->ready[x], NULL, 0);
 
if (slice < POSIXSTAR_MINIMUM_SLICE) slice = POSIXSTAR_MINIMUM_SLICE;
if (slice > POSIXSTAR_MAXIMUM_SLICE) slice = POSIXSTAR_MAXIMUM_SLICE;
lev->slice = slice;
lev->activated=NIL;
lev->budget = budget;
lev->scheduling_level = master;
//lev->multiboot = mb;
 
//if (createmain)
// sys_atrunlevel(POSIXSTAR_call_main,(void *) l, RUNLEVEL_INIT);
 
return l;
}
 
/*+ this function forces the running task to go to his queue tail;
(it works only on the POSIX level) +*/
int POSIXSTAR_sched_yield(LEVEL l)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
if (proc_table[exec_shadow].task_level != l)
return -1;
 
proc_table[exec_shadow].context = kern_context_save();
lev->yielding = 1;
scheduler();
kern_context_load(proc_table[exec_shadow].context);
return 0;
}
 
/*+ this function returns the maximum level allowed for the POSIX level +*/
int POSIXSTAR_get_priority_max(LEVEL l)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
return lev->maxpriority;
}
 
/*+ this function returns the default timeslice for the POSIX level +*/
int POSIXSTAR_rr_get_interval(LEVEL l)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
return lev->slice;
}
 
/*+ this functions returns some paramaters of a task;
policy must be NRT_RR_POLICY or NRT_FIFO_POLICY;
priority must be in the range [0..prioritylevels]
returns ENOSYS or ESRCH if there are problems +*/
int POSIXSTAR_getschedparam(LEVEL l, PID p, int *policy, int *priority)
{
if (p<0 || p>= MAX_PROC || proc_table[p].status == FREE)
return ESRCH;
 
if (proc_table[p].task_level != l)
return ENOSYS;
 
if (proc_table[p].control & CONTROL_CAP)
*policy = NRT_RR_POLICY;
else
*policy = NRT_FIFO_POLICY;
 
*priority = ((POSIXSTAR_level_des *)(level_table[l]))->priority[p];
 
return 0;
}
 
/*+ this functions sets paramaters of a task +*/
int POSIXSTAR_setschedparam(LEVEL l, PID p, int policy, int priority)
{
POSIXSTAR_level_des *lev = (POSIXSTAR_level_des *)(level_table[l]);
 
if (p<0 || p>= MAX_PROC || proc_table[p].status == FREE)
return ESRCH;
 
if (proc_table[p].task_level != l)
return ENOSYS;
 
if (policy == SCHED_RR)
proc_table[p].control |= CONTROL_CAP;
else if (policy == SCHED_FIFO)
proc_table[p].control &= ~CONTROL_CAP;
else
return EINVAL;
 
if (lev->priority[p] != priority) {
if (proc_table[p].status == POSIXSTAR_READY) {
iq_extract(p,&lev->ready[lev->priority[p]]);
lev->priority[p] = priority;
iq_insertlast(p,&lev->ready[priority]);
}
else
lev->priority[p] = priority;
}
 
return 0;
}
 
 
 
/advdemos/branches/advdemos/first/makefile
0,0 → 1,35
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS= test1 test2 test3 test4 test5 test6 test7 testiq
 
include $(BASE)/config/example.mk
 
test1:
make -f $(SUBMAKE) APP=test1 INIT= OTHEROBJS="edfstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test2:
make -f $(SUBMAKE) APP=test2 INIT= OTHEROBJS="edfstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test3:
make -f $(SUBMAKE) APP=test3 INIT= OTHEROBJS="edfstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test4:
make -f $(SUBMAKE) APP=test4 INIT= OTHEROBJS="edfstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test5:
make -f $(SUBMAKE) APP=test5 INIT= OTHEROBJS="edfstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test6:
make -f $(SUBMAKE) APP=test6 INIT= OTHEROBJS="rmstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
test7:
make -f $(SUBMAKE) APP=test7 INIT= OTHEROBJS="posixstar.o cbsstar.o" OTHERINCL= SHARKOPT=__OLDCHAR__
 
#testiq:
# make -f $(SUBMAKE) APP=testiq INIT= OTHEROBJS="iqueue.o " OTHERINCL=
/advdemos/branches/advdemos/first/edfstar.h
0,0 → 1,138
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: edfstar.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
Title:
EDFSTAR
 
Task Models Accepted:
HARD_TASK_MODEL - Hard Tasks (only Periodic)
wcet field and mit field must be != 0. They are used to set the wcet
and period of the tasks.
periodicity field can be only PERIODIC
drel field is ignored
Guest Models Accepted:
JOB_TASK_MODEL - a single guest task activation
Identified by an absolute deadline and a period.
period field is ignored
 
Description:
 
This module schedule his tasks following the classic EDF
scheme. This module is derived from the EDFACT Scheduling Module.
 
This module can not stay alone: when it have to schedule a task, it
simply inserts it into another master module using a
BUDGET_TASK_MODEL.
 
No Task guarantee is performed at all.
The tasks scheduled are only periodic.
All the task are put in a queue and the scheduling is based on the
deadline value.
If a task miss a deadline a counter is incremented.
If a task exausts the wcet a counter is incremented
No ZOMBIE support!!!!!!
 
Exceptions raised:
XUNVALID_GUEST XUNVALID_TASK
some primitives are not implemented:
task_sleep, task_delay, guest_endcycle, guest_sleep, guest_delay
 
XACTIVATION
If a task is actiated through task_activate or guest_activate more than
one time
Restrictions & special features:
- This level doesn't manage the main task.
- Functions to return and reset the nact, wcet and dline miss
counters are provided
 
**/
 
/*
* Copyright (C) 2001 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __EDFSTAR_H__
#define __EDFSTAR_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
 
 
 
/* flags... */
#define EDFSTAR_ENABLE_GUARANTEE 1 /* Task Guarantee enabled */
#define EDFSTAR_ENABLE_ALL 1
 
#define EDFSTAR_FAILED_GUARANTEE 8 /* used in the module, unsettabl
in EDF_register_level... */
 
 
 
#define EDFSTAR_LEVELNAME "EDFSTAR base"
#define EDFSTAR_LEVEL_CODE 166
#define EDFSTAR_LEVEL_VERSION 1
 
 
/* Registration function:
int budget The budget used by this module (see CBSSTAR.h)
int master The master module used by EDFSTAR
*/
LEVEL EDFSTAR_register_level(int budget, int master);
 
/* returns respectively the number of dline, wcet or nact; -1 if error */
int EDFSTAR_get_dline_miss(PID p);
int EDFSTAR_get_wcet_miss(PID p);
int EDFSTAR_get_nact(PID p);
 
/* resets respectively the number of dline, wcet miss; -1 if error */
int EDFSTAR_reset_dline_miss(PID p);
int EDFSTAR_reset_wcet_miss(PID p);
 
#endif
 
/advdemos/branches/advdemos/first/iqueue.c
0,0 → 1,221
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: iqueue.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
 
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "iqueue.h"
#include <kernel/mem.h>
 
void iq_init (IQUEUE *q, IQUEUE *share, int flags)
{
q->first = NIL;
q->last = NIL;
 
if (share)
q->s = share->s;
else {
q->s = (struct IQUEUE_shared *)kern_alloc(sizeof(struct IQUEUE_shared));
 
if (!(flags & IQUEUE_NO_PRIORITY))
q->s->priority = (DWORD *)kern_alloc(sizeof(DWORD) * MAX_PROC);
if (!(flags & IQUEUE_NO_TIMESPEC))
q->s->timespec_priority = (struct timespec *)
kern_alloc(sizeof(struct timespec) * MAX_PROC);
}
}
 
/*+
This function insert the task with PID i in the queue que.
The insertion is made respecting the priority field.
(the first item in the queue have the less priority)
+*/
void iq_priority_insert (PID i, IQUEUE *que)
{
DWORD prio;
PID p,q;
p = NIL;
q = que->first;
prio = que->s->priority[i];
while ((q != NIL) && (prio >= que->s->priority[q])) {
p = q;
q = que->s->next[q];
}
if (p != NIL)
que->s->next[p] = i;
else
que->first = i;
if (q != NIL)
que->s->prev[q] = i;
else
que->last = i;
que->s->next[i] = q;
que->s->prev[i] = p;
}
 
 
/*
This function insert the task with PID i in the queue que.
The insertion is made respecting the timespec priority field.
(the first item in the queue have the less priority)
*/
void iq_timespec_insert(PID i, IQUEUE *que)
{
struct timespec prio;
PID p,q;
 
p = NIL;
q = que->first;
 
TIMESPEC_ASSIGN(&prio, &que->s->timespec_priority[i]);
while ((q != NIL) &&
!TIMESPEC_A_LT_B(&prio, &que->s->timespec_priority[q])) {
p = q;
q = que->s->next[q];
}
if (p != NIL)
que->s->next[p] = i;
else
que->first = i;
if (q != NIL)
que->s->prev[q] = i;
else
que->last = i;
que->s->next[i] = q;
que->s->prev[i] = p;
}
 
 
 
void iq_insertfirst(PID p, IQUEUE *q)
{
if (q->first != NIL) {
q->s->next[p] = q->first;
q->s->prev[q->first] = p;
}
else {
q->last = p;
q->s->next[p] = NIL;
}
q->s->prev[p] = NIL;
q->first = p;
}
 
 
void iq_insertlast(PID p, IQUEUE *q)
{
if (q->last != NIL) {
q->s->prev[p] = q->last;
q->s->next[q->last] = p;
}
else {
q->first = p;
q->s->prev[p] = NIL;
}
q->s->next[p] = NIL;
q->last = p;
}
 
 
void iq_extract(PID i, IQUEUE *que)
{
PID p,q;
p = que->s->prev[i];
q = que->s->next[i];
if (p != NIL)
que->s->next[p] = que->s->next[i];
else
que->first = q;
if (q != NIL)
que->s->prev[q] = que->s->prev[i];
else
que->last = p;
}
 
PID iq_getfirst(IQUEUE *q)
{
PID p = q->first;
if (p == NIL)
return NIL;
 
q->first = q->s->next[q->first];
 
if (q->first != NIL)
q->s->prev[q->first] = NIL;
else
q->last = NIL;
return p;
}
 
PID iq_getlast(IQUEUE *q)
{
PID p = q->last;
if (p == NIL)
return NIL;
 
q->last = q->s->prev[q->last];
 
if (q->last != NIL)
q->s->next[q->last] = NIL;
else
q->first = NIL;
return p;
}
/advdemos/branches/advdemos/chimera/udpdump.c
0,0 → 1,115
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>/* close() */
#include <stdlib.h>
#include <signal.h>
#include <string.h>
 
#define SERVER_PORT 20000
#define MAX_MSG 10000
 
FILE *output_file;
 
int miss;
 
void close_and_exit()
{
 
printf("Closing...\n");
 
if (miss == 1) printf("Possible error receiving packets !\n");
 
fclose(output_file);
 
exit(0);
 
}
 
int main(int argc, char *argv[])
{
int sd, rc, n, cliLen,count;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];
 
if (argc < 2) {
printf("%s: Enter the output file name [%s filename]\n",argv[0],argv[0]);
exit(1);
}
 
// socket creation
sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd < 0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}
 
output_file = fopen(argv[1],"w+b");
if (output_file == NULL) {
printf("%s: Cannot open the file\n",argv[0]);
exit(1);
}
 
// bind local server port
servAddr.sin_family = AF_INET;
 
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(SERVER_PORT);
 
rc = bind (sd, (struct sockaddr *)&servAddr,sizeof(servAddr));
if(rc < 0) {
printf("%s: cannot bind port number %d \n",
argv[0], SERVER_PORT);
exit(1);
}
 
signal(SIGINT, close_and_exit);
 
count = 1;
miss = 0;
 
while(1) {
 
printf("Wait packet...\n");
 
// receive message
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *)&cliAddr, &cliLen);
 
if (n > 0) {
 
count++;
 
fwrite((void *)(msg),n,1,output_file);
}
 
}
 
fclose(output_file);
 
return 0;
 
}
 
/advdemos/branches/advdemos/chimera/linux.c
0,0 → 1,130
#include <stdio.h>
#include <math.h>
 
#define LEG_A 100.0
#define LEG_B 66.0
#define LEG_C 26.0
#define LEG_D 38.0
#define LEG_CD_2IPO 92.087 /* 2 * sqrt(LEG_C^2 + LEG_D^2) */
#define LEG_CD_ANG 0.600 /* arctg(LEG_C/LEG_D) in radianti */
 
#define PI 3.1415
 
const float c0 = LEG_C * LEG_C;
const float c1 = LEG_B * LEG_B;
const float c2 = LEG_B * LEG_B - LEG_A * LEG_A;
const float todeg = 180.0 / PI;
const float torad = PI / 180.0;
 
int leg_to_ang(float px, float py, float pz, int *alfa, int *beta, int *gamma)
{
float px2 = px * px;
float py2 = py * py;
float pz2 = pz * pz;
 
float pxz2 = px2 + pz2;
 
float alfa1,beta1,alfa2,beta2,gamma1,gamma2;
float m,dsqrt;
 
float delta_xz = pxz2 - c0;
float s,k,k2,y1,delta_xy;
 
if (delta_xz < 0.0) return -1;
 
if (pz >= LEG_C) {
gamma2 = acos((pz * LEG_C + px * sqrt(delta_xz)) / pxz2);
gamma1 = gamma2 * todeg;
} else {
gamma2 = -acos((pz * LEG_C + px * sqrt(delta_xz)) / pxz2);
gamma1 = gamma2 * todeg;
}
 
m = pxz2 - LEG_CD_2IPO * (px * cos(gamma2+LEG_CD_ANG) + pz * sin(gamma2+LEG_CD_ANG) - LEG_CD_2IPO/4);
 
printf("M = %f\n",sqrt(m));
 
s = m + py2;
k = c2 + s;
k2 = k * k;
delta_xy = py2 * k2 - s * (k2 - 4.0 * m * c1);
 
if (delta_xy >= 0.0) {
dsqrt = sqrt(delta_xy);
y1 = (py * k + dsqrt) / (2.0 * s);
beta1 = asin(y1/LEG_B) * todeg;
alfa1 = asin((y1 - py)/LEG_A) * todeg + beta1;
y1 = (py * k - dsqrt) / (2.0 * s);
beta2 = asin(y1/LEG_B) * todeg;
alfa2 = asin((y1 - py)/LEG_A) * todeg + beta2;
 
if ((alfa1 >= 0.0 && alfa1 <= 180.0) && (beta1 >= -90.0 && beta1 <= 90.0)) {
*alfa = (int)(alfa1 * 3600.0);
*beta = (int)(beta1 * 3600.0);
*gamma = (int)(gamma1 * 3600.0);
return 0;
} else if ((alfa2 >= 0.0 && alfa2 <= 180.0) && (beta2 >= -90.0 && beta2 <= 90.0)) {
*alfa = (int)(alfa2 * 3600.0);
*beta = (int)(beta2 * 3600.0);
*gamma = (int)(gamma1 * 3600.0);
return 0;
} else {
return -1;
}
} else
return -1;
 
return -1;
 
}
 
int ang_to_leg(int alfa, int beta, int gamma, float *px, float *py, float *pz) {
 
float alfa1 = (float)(alfa)/3600.0 * torad;
float beta1 = (float)(beta)/3600.0 * torad;
float sin_gamma = sin((float)(gamma)/3600.0 * torad);
float cos_gamma = cos((float)(gamma)/3600.0 * torad);
float m;
m = LEG_B * cos(beta1) + LEG_A * cos(alfa1 - beta1);
*py = LEG_B * sin(beta1) - LEG_A * sin(alfa1 - beta1);
 
*pz = (LEG_D + m) * sin_gamma + LEG_C * cos_gamma;
*px = (LEG_D + m) * cos_gamma - LEG_C * sin_gamma;
 
return 0;
 
}
 
int main() {
 
float px,py,pz;
int a,b,c;
 
while(1) {
 
printf("Insert PX: ");
scanf("%f",&px);
 
printf("Insert PY: ");
scanf("%f",&py);
 
printf("Insert PZ: ");
scanf("%f",&pz);
 
printf("PX: %3.3f PY: %3.3f PZ: %3.3f\n",px,py,pz);
 
if (leg_to_ang(px,py,pz,&a,&b,&c))
printf("Error leg position\n");
 
ang_to_leg(a,b,c,&px,&py,&pz);
 
printf(" A: %7d B: %7d C: %7d\n",a/3600,b/3600,c/3600);
printf("PX: %.3f PY: %.3f PZ: %.3f\n",px,py,pz);
 
}
 
return 0;
 
}
/advdemos/branches/advdemos/chimera/initfile.c
0,0 → 1,66
/*
* Project: HARTIK (HA-rd R-eal TI-me K-ernel)
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Gerardo Lamastra <gerardo@sssup.it>
*
* Authors : Mauro Marinoni <mauro.marinoni@unipv.it>
* Giacomo Guidi <giacomo@gandalf.sssup.it>
* (see authors.txt for full list of hartik's authors)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://hartik.sssup.it
*/
 
#include "chimera.h"
#include "modules/edf.h"
#include "modules/hardcbs.h"
#include "modules/rr.h"
#include "modules/dummy.h"
#include "modules/intdrive.h"
 
#include <drivers/keyb.h>
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
#define INTDRIVE_Q 1000
#define INTDRIVE_T 10000
#define INTDRIVE_FLAGS 0
 
int main(int argc, char **argv);
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDF_register_level(EDF_ENABLE_ALL);
HCBS_register_level(HCBS_ENABLE_ALL, 0);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
SEM_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
/advdemos/branches/advdemos/chimera/calibrate.c
0,0 → 1,188
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
*
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "chimera.h"
#include <ll/i386/64bit.h>
 
volatile int calibrate_status = 0;
volatile int calibrate_exec_step = 0;
 
extern HEXAPOD_STATE status;
extern unsigned char active_leg;
 
struct leg_calibration {
int side;
int pos[6];
int delta_90[3];
int zero[3];
};
 
struct leg_calibration calibration_table[] = {
{1,{0,90,-45,45,-90,0},{432001,403201,432001},{-201600,28800,241201}},
{-1,{0,90,-45,45,-90,0},{413949,453599,431999},{216000,50401,-215599}},
{1,{0,90,-45,45,-45,45},{417601,388801,424741},{-216000,-43200,82770}},
{-1,{0,90,-45,45,-45,45},{421199,421199,443799},{165600,-8999,30600}},
{1,{0,90,-45,45,0,90},{414001,424801,410401},{-162000,39600,-122400}},
{-1,{0,90,-45,45,0,90},{410399,446399,399599},{154800,-3599,108000}},
};
 
int adjust(int angle_sec, int leg, int num) {
 
int temp;
 
smul32div32to32(angle_sec,calibration_table[leg].delta_90[num],324000,temp);
 
return calibration_table[leg].side * temp + calibration_table[leg].zero[num];
}
 
TASK calibrate(void *arg) {
 
int i, num = 0, angsec = 0, angsec_temp[6];
static int test_angle[20],set,turn_on,servo_count;
char servo_name[10];
 
for (i=0;i<20;i++) test_angle[i] = 0;
 
clear();
servo_turn_off(com(active_leg*3), pin(active_leg*3));
servo_turn_off(com(active_leg*3+1), pin(active_leg*3+1));
servo_turn_off(com(active_leg*3+2), pin(active_leg*3+2));
 
servo_count = 0;
servo_turn_on(com(active_leg*3), pin(active_leg*3));
turn_on = 0;
 
while (calibrate_status == 1) {
 
if (calibrate_exec_step == 100000) {
angsec_temp[servo_count] = test_angle[3*active_leg+num];
printf_xy(0,10+servo_count,WHITE,"%08d",test_angle[3*active_leg+num]);
servo_turn_off(com(3*active_leg+num),pin(3*active_leg+num));
servo_count++;
 
if (servo_count == 6) {
 
for (i=0;i<3;i++) {
calibration_table[active_leg].delta_90[i] = abs(angsec_temp[2*i+1] - angsec_temp[2*i] + 1);
calibration_table[active_leg].zero[i] = calibration_table[active_leg].side * abs(calibration_table[active_leg].pos[2*i] * calibration_table[active_leg].delta_90[i] / 90) + angsec_temp[2*i];
 
printf_xy(22*i,22,WHITE,"D%d %7d Z%d %7d",
i,calibration_table[active_leg].delta_90[i],
i,calibration_table[active_leg].zero[i]);
 
}
 
calibrate_status = 0;
calibrate_exec_step = 0;
 
task_kill(exec_shadow);
task_testcancel();
 
}
 
turn_on = 1;
 
calibrate_exec_step = 0;
 
}
 
switch (servo_count) {
case 0:
case 1:
sprintf(servo_name,"ALFA ");
num = 0;
break;
case 2:
case 3:
sprintf(servo_name,"BETA ");
num = 1;
break;
case 4:
case 5:
sprintf(servo_name,"GAMMA");
num = 2;
break;
}
 
if (turn_on == 1) {
servo_turn_on(com(3*active_leg+num),pin(3*active_leg+num));
turn_on = 0;
}
 
set = calibration_table[active_leg].pos[servo_count];
printf_xy(10,10+servo_count,WHITE,"Set servo %s to position %d",servo_name,set);
servo_turn_on(com(3*active_leg+num),pin(3*active_leg+num));
 
if (calibrate_exec_step != 0) {
test_angle[3*active_leg+num] += calibrate_exec_step;
printf_xy(10,20,WHITE,"Set %08d to servo %03d",test_angle[3*active_leg+num],3*active_leg+num);
servo_set_angle_sec(com(3*active_leg+num), pin(3*active_leg+num), test_angle[3*active_leg+num]);
 
calibrate_exec_step = 0;
 
}
 
angsec = servo_get_angle_sec(com(3*active_leg+num), pin(3*active_leg+num));
printf_xy(10,21,WHITE,"Angle Seconds = %08d",angsec);
 
task_endcycle();
 
}
 
return 0;
 
}
 
void calibrate_init() {
 
SOFT_TASK_MODEL st;
PID st_pid;
 
if (calibrate_status == 0) {
calibrate_status = 1;
 
soft_task_default_model(st);
soft_task_def_period(st,300000);
soft_task_def_met(st,30000);
soft_task_def_usemath(st);
soft_task_def_ctrl_jet(st);
 
st_pid = task_create("Calibration task",calibrate,&st,NULL);
if (st_pid == NIL) {
cprintf("Error creating calibration task\n");
sys_end();
}
 
task_activate(st_pid);
 
} else {
return;
}
}
 
void calibrate_step(int step) {
 
if (calibrate_status != 0 && calibrate_exec_step == 0) {
 
calibrate_exec_step = step;
 
}
 
}
/advdemos/branches/advdemos/chimera/chimera.c
0,0 → 1,293
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "chimera.h"
 
#define POS_B_REF 0
#define POS_B_UP 50
 
int vel_dx = 15;
int vel_sx = 15;
 
void program_key_end(KEY_EVT* e)
{
 
int i;
TIME tmp;
 
end_send();
 
for (i=3; i<MAX_PROC; i++){
if (!jet_getstat(i, NULL, &tmp, NULL, NULL))
kern_printf("Task Name : %s - Max Time : %d\n", proc_table[i].name, (int)tmp);
}
 
trace_send();
 
sys_end();
 
}
 
int beta = 30;
 
void action_stand_up(void) {
struct action_event e;
int event,alfa;
status.power = 1;
 
kern_gettime(&(e.time));
 
for (alfa=0;alfa<=90;alfa+=15) {
 
ADDUSEC2TIMESPEC(5000000,&(e.time));
e.type = EVT_SET_MASK_LEG_ANGLE;
e.mask = 0x3F;
e.ang.a = alfa * 3600;
e.ang.b = beta * 3600;
e.ang.c = 0 * 3600;
e.pwm = 7;
event = insert_action_event(&(e));
cprintf("Event num = %d\n",event);
 
}
 
}
 
TASK walk_auto_6()
{
short i, n;
int vd, vs, auto_count = 0;
int pos_a[6], pos_b[6], pos_c[6];
struct action_event e;
 
float fake_sin[36] = { .00, .50, .80, 1.0, .80, .50, .00, .00, .00, .00, .00, .00,
.00, .00, .00, .00, .00, .00, .00, .00, .00, .00, .00, .00,
.00, .00, .00, .00, .00, .00, .00, .00, .00, .00, .00, .00};
 
float fake_cos[36] = {-1.0,-.75,-.50, .00, .50, .75, 1.0, .93, .86, .80, .73, .66,
.60, .53, .46, .40, .33, .26, .20, .13, .06, .00,-.06, .13,
-.20,-.26,-.33,-.40,-.46,-.53,-.60,-.66,-.73,-.80,-.86,-.93};
 
while (1) {
vd = vel_dx;
vs = vel_sx;
 
kern_gettime(&(e.time));
ADDUSEC2TIMESPEC(10000,&(e.time));
for (i = 0; i<6; i++) {
switch(i) {
case 0:
n = 0;
break;
case 1:
n = 3;
break;
case 2:
n = 4;
break;
case 3:
n = 1;
break;
case 4:
n = 2;
break;
case 5:
n = 5;
break;
}
if (i%3)
pos_c[i] = vd * fake_cos[(auto_count+6*n)%36];
else
pos_c[i] = vs * fake_cos[(auto_count+6*n)%36];
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[(auto_count+6*n)%36] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
 
e.type = EVT_SET_MASK_LEG_ANGLE;
e.mask = 1 << i;
e.ang.a = (80) * 3600;
e.ang.b = (pos_b[i]) * 3600;
e.ang.c = (pos_c[i]) * 3600;
e.pwm = 7;
insert_action_event(&(e));
}
auto_count++;
if (auto_count > 35) auto_count = 0;
 
task_testcancel();
task_endcycle();
}
return 0;
}
 
TASK walk_auto_3()
{
short i;
int vd, vs, auto_count = 0;
float cos_a;
int pos_a[6], pos_b[6], pos_c[6];
 
struct action_event e;
 
 
float fake_cos[32] = { 1.0000, .99518, .98079, .95694, .92388, .88192, .83147, .77301,
.70711, .63439, .55557, .47140, .38268, .29028, .19509, .09802,
.00000,-.09802,-.19509,-.29028,-.38268,-.47140,-.55557,-.63439,
-.70711,-.77301,-.83147,-.88192,-.92388,-.95694,-.98079,-.99518};
float fake_sin[64] = { -0.50, -0.45, -0.40, -0.30, -0.20, -0.15, -0.10, -0.05,
0.00, 0.00, 0.40, 0.40, 0.70, 0.70, 0.90, 0.90,
1.00, 1.00, 0.90, 0.90, 0.70, 0.70, 0.40, 0.40,
0.00, 0.00, -0.05, -0.10, -0.15, -0.20, -0.30, -0.40,
-0.45, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50,
-0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50,
-0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50,
-0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50, -0.50 };
 
while (1) {
cos_a = (auto_count < 32) ? fake_cos[auto_count] : -fake_cos[auto_count-32];
 
vd = vel_dx;
vs = vel_sx;
 
kern_gettime(&(e.time));
ADDUSEC2TIMESPEC(10000,&(e.time));
for (i = 0; i<6; i++) {
switch (i) {
case 0:
/* Leg 0 */
pos_c[i] = vs * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[(auto_count+32)%64] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
case 1:
/* Leg 1 */
pos_c[i] = -vd * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[auto_count] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
case 2:
/* Leg 2 */
pos_c[i] = -vs * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[auto_count] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
case 3:
/* Leg 3 */
pos_c[i] = vd * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[(auto_count+32)%64] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
case 4:
/* Leg 4 */
pos_c[i] = vs * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[(auto_count+32)%64] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
case 5:
/* Leg 5 */
pos_c[i] = -vd * cos_a;
if ((vs) || (vd))
pos_b[i] = POS_B_REF + fake_sin[auto_count] * POS_B_UP;
else
pos_b[i] = POS_B_REF;
break;
}
 
e.type = EVT_SET_MASK_LEG_ANGLE;
e.mask = 1 << i;
e.ang.a = (80) * 3600;
e.ang.b = (pos_b[i]) * 3600;
e.ang.c = (pos_c[i]) * 3600;
e.pwm = 7;
insert_action_event(&(e));
}
 
auto_count += 4;
if (auto_count > 63) auto_count = 0;
 
task_testcancel();
task_endcycle();
}
return 0;
}
 
void action_walk(void) {
HARD_TASK_MODEL ms;
PID pid_walk;
hard_task_default_model(ms);
hard_task_def_ctrl_jet(ms);
hard_task_def_wcet(ms, 1000);
hard_task_def_mit(ms, 30000);
hard_task_def_usemath(ms);
pid_walk = task_create("Walk_Task", walk_auto_3, &ms, NULL);
if (pid_walk == NIL) {
perror("Could not create task <Walk_Auto>");
sys_end();
} else
task_activate(pid_walk);
}
 
int main(int argc, char **argv)
{
TIME seme;
KEY_EVT k;
 
seme = sys_gettime(NULL);
srand(seme);
 
k.flag = ALTL_BIT;
k.scan = KEY_C;
k.ascii = 'c';
keyb_hook(k,program_key_end);
 
clear();
 
trace_init(1000000);
 
init_send(); /* Comunication */
init_key(); /* Keyboard */
 
init_action_event(100);
 
if (argc < 2) sys_end();
 
beta = atoi(argv[1]);
cprintf("Beta = %d\n",beta);
 
//action_stand_up();
action_walk();
 
return 0;
 
}
/advdemos/branches/advdemos/chimera/send.c
0,0 → 1,453
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "chimera.h"
#include "tracer.h"
#include "unistd.h"
 
//#define DEBUG_SEND /* Print Sent Values */
#define SERIAL_ON /* Send Data using Serial Port */
 
/* Servo Tasks Constants */
#ifdef DUBUG_SEND
#define SEND_TASK_WCET 26000
#else
#define SEND_TASK_WCET 26000
#endif
#define SEND_TASK_MIT 30000
 
#define LEG_A 100.0
#define LEG_B 66.0
#define LEG_C 26.0
#define LEG_D 38.0
#define LEG_CD_2IPO 92.087 /* 2 * sqrt(LEG_C^2 + LEG_D^2) */
#define LEG_CD_ANG 0.600 /* arctg(LEG_C/LEG_D) in radianti */
 
const float c0 = LEG_C * LEG_C;
const float c1 = LEG_B * LEG_B;
const float c2 = LEG_B * LEG_B - LEG_A * LEG_A;
const float todeg = 180.0 / PI;
const float torad = PI / 180.0;
 
HEXAPOD_STATE status;
 
void *start_tracer = NULL;
void *end_tracer = NULL;
void *trace_pointer = NULL;
 
extern struct leg_calibration calibration_table[];
 
void print_status(int n){
}
 
int leg_to_ang(float px, float py, float pz, int *alfa, int *beta, int *gamma)
{
float px2 = px * px;
float py2 = py * py;
float pz2 = pz * pz;
 
float pxz2 = px2 + pz2;
 
float alfa1,beta1,alfa2,beta2,gamma1,gamma2;
float m,dsqrt;
 
float delta_xz = pxz2 - c0;
float s,k,k2,y1,delta_xy;
 
if (delta_xz < 0.0) return -1;
 
if (pz >= LEG_C) {
gamma2 = acos((pz * LEG_C + px * sqrt(delta_xz)) / pxz2);
gamma1 = gamma2 * todeg;
} else {
gamma2 = -acos((pz * LEG_C + px * sqrt(delta_xz)) / pxz2);
gamma1 = gamma2 * todeg;
}
 
m = pxz2 - LEG_CD_2IPO * (pz * sin(gamma2+LEG_CD_ANG) + px * cos(gamma2+LEG_CD_ANG) - LEG_CD_2IPO / 4.0);
 
s = m + py2;
k = c2 + s;
k2 = k * k;
delta_xy = py2 * k2 - s * (k2 - 4.0 * m * c1);
 
if (delta_xy >= 0.0) {
dsqrt = sqrt(delta_xy);
y1 = (py * k + dsqrt) / (2.0 * s);
beta1 = asin(y1/LEG_B) * todeg;
alfa1 = asin((y1 - py)/LEG_A) * todeg + beta1;
y1 = (py * k - dsqrt) / (2.0 * s);
beta2 = asin(y1/LEG_B) * todeg;
alfa2 = asin((y1 - py)/LEG_A) * todeg + beta2;
 
if ((alfa1 >= 0.0 && alfa1 <= 180.0) && (beta1 >= -90.0 && beta1 <= 90.0)) {
*alfa = (int)(alfa1 * 3600.0);
*beta = (int)(beta1 * 3600.0);
*gamma = (int)(gamma1 * 3600.0);
return 0;
} else if ((alfa2 >= 0.0 && alfa2 <= 180.0) && (beta2 >= -90.0 && beta2 <= 90.0)) {
*alfa = (int)(alfa2 * 3600.0);
*beta = (int)(beta2 * 3600.0);
*gamma = (int)(gamma1 * 3600.0);
return 0;
} else {
return -1;
}
} else
return -1;
 
return -1;
 
}
 
int ang_to_leg(int alfa, int beta, int gamma, float *px, float *py, float *pz) {
 
float alfa1 = (float)(alfa)/3600.0 * torad;
float beta1 = (float)(beta)/3600.0 * torad;
float sin_gamma = sin((float)(gamma)/3600.0 * torad);
float cos_gamma = cos((float)(gamma)/3600.0 * torad);
float m;
m = LEG_B * cos(beta1) + LEG_A * cos(alfa1 - beta1);
*py = LEG_B * sin(beta1) - LEG_A * sin(alfa1 - beta1);
 
*pz = (LEG_D + m) * sin_gamma + LEG_C * cos_gamma;
*px = (LEG_D + m) * cos_gamma - LEG_C * sin_gamma;
 
return 0;
 
}
 
void update_event_action(void) {
 
struct timespec t;
struct action_event *e;
int i;
 
kern_gettime(&t);
 
while ((e = get_first_old_event(&t)) != NULL) {
 
if (e->type == EVT_SET_MASK_LEG_ANGLE) {
 
for (i=0;i<6;i++)
if ((e->mask >> i) & 1) {
 
status.ang[i].a = e->ang.a;
status.ang[i].b = e->ang.b;
status.ang[i].c = e->ang.c;
 
status.cfg[i].pwm = e->pwm;
 
#ifdef DEBUG_SEND
printf_xy(3,2,WHITE,"%8d: Update leg %2d angle",(int)kern_gettime(NULL),i);
#endif
 
 
}
 
e->status = EVT_STATUS_DONE;
 
}
 
}
 
}
 
int trace_init(int buffer_size)
{
 
start_tracer = trace_pointer = (void *)malloc(buffer_size);
end_tracer = start_tracer + buffer_size;
memset(trace_pointer,0,buffer_size);
 
if (trace_pointer == NULL) return -1;
 
return 0;
}
 
/* Init the network stack */
int init_network(char *local_ip)
{
struct net_model m = net_base;
net_setudpip(m, local_ip, "255.255.255.255");
if (net_init(&m) != 1) {
cprintf("Network: Init Error.\n");
return -1;
}
return 0;
}
 
int trace_consumption(int sensor, int value)
{
 
struct timespec t;
SYS_FLAGS f;
 
if (trace_pointer == NULL) return -1;
 
if (trace_pointer >= (end_tracer-16)) return -1;
 
f = kern_fsave();
 
sys_gettime(&t);
 
*(unsigned int *)trace_pointer = (sensor & 0xFF) | 0xAABBFF00;
*(unsigned int *)(trace_pointer + 4) = value;
*(unsigned int *)(trace_pointer + 8) = t.tv_sec;
*(unsigned int *)(trace_pointer + 12) = t.tv_nsec;
 
trace_pointer += 16;
 
kern_frestore(f);
 
return 0;
 
}
 
int trace_send() {
 
static char pkg_buffer[1100];
int actual = 0;
 
UDP_ADDR target, local;
char local_ip[20], target_ip[20];
int socket;
IP_ADDR bindlist[5];
strcpy(local_ip, "192.168.0.99");
strcpy(target_ip, "192.168.0.104");
if (init_network(local_ip)) sys_end();
/* local IP string to addr */
ip_str2addr(local_ip,&(local.s_addr));
/* set the source port */
local.s_port = 20000;
/* target IP string to addr */
ip_str2addr(target_ip,&(bindlist[0]));
memset(&(bindlist[1]), 0, sizeof(IP_ADDR));
/* bind */
socket = udp_bind(&local, NULL);
/* target IP string to addr */
ip_str2addr(target_ip,&(target.s_addr));
/* target port */
target.s_port = 20000;
 
trace_pointer = start_tracer;
actual = 0;
 
while(trace_pointer < end_tracer) {
 
if (((*(int *)(trace_pointer) >> 8) & 0xAABBFF) == 0xAABBFF) {
 
cprintf(".");
 
memcpy(&(pkg_buffer[actual]),trace_pointer,16);
 
actual += 16;
 
if (actual > 800) {
pkg_buffer[actual] = 0;
cprintf("X");
udp_sendto(socket, pkg_buffer, actual, &target);
usleep(100000);
actual = 0;
}
 
}
 
trace_pointer += 16;
 
}
 
pkg_buffer[actual] = 0;
cprintf("X");
udp_sendto(socket, pkg_buffer, actual+1, &target);
usleep(10000);
actual = 0;
 
return 0;
 
}
 
TASK servo_send()
{
HEXAPOD_STATE old_status;
register char new_pos, new_pwm, new_power;
int res,n;
struct timespec t;
int actual_leg = 0;
 
for (n=0; n<6;n++) {
old_status.ang[n].a = 0;
old_status.ang[n].b = 0;
old_status.ang[n].c = 0;
old_status.cfg[n].pwm = 0;
}
old_status.power = 0;
 
while (1) {
new_pos = 0;
new_pwm = 0;
new_power = 0;
 
update_event_action();
 
if (status.power != old_status.power) {
#ifdef SERIAL_ON
task_nopreempt();
if (old_status.power) {
servo_set_RC5_switch(COM2, 1);
} else {
servo_set_RC5_switch(COM2, 0);
}
task_preempt();
old_status.power = status.power;
#endif
}
 
for (n=0; n<6; n++){
#ifdef SERIAL_ON
task_nopreempt();
status.cfg[actual_leg].adc_in = servo_get_analog(COM1, actual_leg);
trace_consumption(actual_leg,status.cfg[actual_leg].adc_in);
task_preempt();
#endif
sys_gettime(&t);
printf_xy(1,20,WHITE,"(%d) (%d) (%d) (%d) (%d) (%d) ",
status.cfg[0].adc_in,
status.cfg[1].adc_in,
status.cfg[2].adc_in,
status.cfg[3].adc_in,
status.cfg[4].adc_in,
status.cfg[5].adc_in);
actual_leg = (actual_leg+1)%6;
 
if ((status.ang[n].a != old_status.ang[n].a) ||
(status.ang[n].b != old_status.ang[n].b) ||
(status.ang[n].c != old_status.ang[n].c)) {
old_status.ang[n].a = status.ang[n].a;
old_status.ang[n].b = status.ang[n].b;
old_status.ang[n].c = status.ang[n].c;
new_pos += 1 << n;
}
 
if (status.cfg[n].pwm != old_status.cfg[n].pwm) {
old_status.cfg[n].pwm = status.cfg[n].pwm;
new_pwm += 1 << n;
}
if (new_pos && (1<<n)) {
#ifdef SERIAL_ON
task_nopreempt();
res = servo_set_angle_sec(com(n*3 ), pin(n*3 ), adjust(status.ang[n].a,n,0));
if (res != 0) cprintf("Error send data\n");
res = servo_set_angle_sec(com(n*3+1), pin(n*3+1), adjust(status.ang[n].b,n,1));
if (res != 0) cprintf("Error send data\n");
res = servo_set_angle_sec(com(n*3+2), pin(n*3+2), adjust(status.ang[n].c,n,2));
if (res != 0) cprintf("Error send data\n");
task_preempt();
#endif
 
}
if (new_pwm && (1<<n)) {
#ifdef SERIAL_ON
task_nopreempt();
(old_status.cfg[n].pwm & 1) ? servo_turn_on(com(n*3 ), pin(n*3 )) : servo_turn_off(com(n*3 ), pin(n*3 ));
(old_status.cfg[n].pwm & 2) ? servo_turn_on(com(n*3+1), pin(n*3+1)) : servo_turn_off(com(n*3+1), pin(n*3+1));
(old_status.cfg[n].pwm & 4) ? servo_turn_on(com(n*3+2), pin(n*3+2)) : servo_turn_off(com(n*3+2), pin(n*3+2));
task_preempt();
#endif
}
}
 
task_testcancel();
task_endcycle();
}
return 0;
}
 
int init_serial()
{
int err;
err = servo_open(COM1, COM_SPEED);
if (!err)
err = servo_open(COM2, COM_SPEED);
 
return err;
}
 
void end_serial()
{
servo_close(COM1);
servo_close(COM2);
}
 
PID servo_pid;
 
void init_send_task()
{
HARD_TASK_MODEL ms;
 
hard_task_default_model(ms);
hard_task_def_ctrl_jet(ms);
hard_task_def_wcet(ms, SEND_TASK_WCET);
hard_task_def_mit(ms, SEND_TASK_MIT);
hard_task_def_usemath(ms);
servo_pid = task_create("Servo_Task", servo_send, &ms, NULL);
if (servo_pid == NIL) {
perror("Could not create task <Send_Task>");
sys_end();
} else
task_activate(servo_pid);
 
}
 
void init_send()
{
int i;
 
if (init_serial()) {
perror("Could not initialize serial port.");
sys_end();
}
 
for (i=0; i<6;i++) {
status.ang[i].a = 0;
status.ang[i].b = 0;
status.ang[i].c = 0;
status.cfg[i].pwm = 0;
}
status.power = 0;
 
init_send_task();
 
}
 
void end_send()
{
task_kill(servo_pid);
 
end_serial();
}
/advdemos/branches/advdemos/chimera/keys.c
0,0 → 1,200
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
*
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "chimera.h"
 
unsigned char active_leg;
 
extern volatile int calibrate_status;
 
void pad(KEY_EVT *k)
{
switch (k->scan) {
case KEY_Z:
status.power ^= 1;
break;
case KEY_Q:
status.cfg[active_leg].pwm ^= 0x1;
break;
case KEY_W:
status.cfg[active_leg].pwm ^= 0x2;
break;
case KEY_E:
status.cfg[active_leg].pwm ^= 0x4;
break;
case KEY_1:
active_leg = 0;
break;
case KEY_2:
active_leg = 1;
break;
case KEY_3:
active_leg = 2;
break;
case KEY_4:
active_leg = 3;
break;
case KEY_5:
active_leg = 4;
break;
case KEY_6:
active_leg = 5;
break;
case KEY_C:
if (calibrate_status != 0) calibrate_step(100000);
else calibrate_init();
break;
 
case KEY_A:
calibrate_step(-108000);
break;
case KEY_S:
calibrate_step(-3600);
break;
case KEY_D:
calibrate_step(-60);
break;
case KEY_F:
calibrate_step(+60);
break;
case KEY_G:
calibrate_step(+3600);
break;
case KEY_H:
calibrate_step(+108000);
break;
}
}
 
void init_key()
{
KEY_EVT k;
 
k.flag = 0;
k.scan = KEY_1;
k.ascii = '1';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_2;
k.ascii = '2';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_3;
k.ascii = '3';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_4;
k.ascii = '4';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_5;
k.ascii = '5';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_6;
k.ascii = '6';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_J;
k.ascii = 'j';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_K;
k.ascii = 'k';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_L;
k.ascii = 'l';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_U;
k.ascii = 'u';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_I;
k.ascii = 'i';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_O;
k.ascii = 'o';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_Q;
k.ascii = 'q';
keyb_hook(k,pad);
k.flag = 0;
k.scan = KEY_W;
k.ascii = 'w';
keyb_hook(k,pad);
k.flag = 0;
k.scan = KEY_E;
k.ascii = 'e';
keyb_hook(k,pad);
k.flag = 0;
k.scan = KEY_Z;
k.ascii = 'z';
keyb_hook(k,pad);
 
 
k.flag = 0;
k.scan = KEY_C;
k.ascii = 'c';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_A;
k.ascii = 'a';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_S;
k.ascii = 's';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_D;
k.ascii = 'd';
keyb_hook(k,pad);
k.flag = 0;
k.scan = KEY_F;
k.ascii = 'f';
keyb_hook(k,pad);
 
k.flag = 0;
k.scan = KEY_G;
k.ascii = 'g';
keyb_hook(k,pad);
k.flag = 0;
k.scan = KEY_H;
k.ascii = 'h';
keyb_hook(k,pad);
}
/advdemos/branches/advdemos/chimera/list.c
0,0 → 1,87
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
 
#define READ_BUFFER 2000
#define DELTA_BUFFER 100
 
int main(int argc, char *argv[])
{
 
char buffer[READ_BUFFER+DELTA_BUFFER];
void *p, *last;
int n,delta,size;
 
unsigned long long ev = 0;
 
FILE *input_file;
if (argc < 2) {
printf("%s: Enter the input file name [%s filename]\n",argv[0],argv[0]);
exit(1);
}
 
input_file = fopen(argv[1],"rb");
 
last = buffer + READ_BUFFER;
 
while(!feof(input_file)) {
//move remaining byte
delta = (unsigned int)(buffer) + READ_BUFFER - (unsigned int)(last);
if (delta > 0) memcpy(buffer,last,delta);
 
n = fread(buffer+delta,1,READ_BUFFER+10,input_file);
fseek(input_file,-(delta+10),SEEK_CUR);
 
p = buffer;
 
while ((unsigned int)(p) + 16 <= (unsigned int)(buffer + READ_BUFFER) &&
(unsigned int)(p) + 16 <= (unsigned int)(buffer + n + delta)) {
 
printf("Sensor = %02x ",(*(unsigned int *)(p) & 0xFF));
 
printf("Current = %8d ",*(unsigned int *)(p+4));
printf("TIME = %8d:%8d\n",*(unsigned int *)(p+8),*(unsigned int *)(p+12));
 
size = 16;
 
ev++;
p += 16;
 
if ((unsigned int)(p) + 10 > (unsigned int)(buffer + n + delta)) break;
 
last = p;
}
 
if ((unsigned int)(p) + 10 > (unsigned int)(buffer + n + delta)) break;
}
 
fclose(input_file);
 
return 0;
 
}
 
/advdemos/branches/advdemos/chimera/makefile
0,0 → 1,24
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS= chimera udpdump list
 
include $(BASE)/config/example.mk
 
chimera:
make -f $(SUBMAKE) APP=chimera INIT= OTHEROBJS="initfile.o calibrate.o send.o action.o keys.o" SHARKOPT="__OLDCHAR__ __SERVO__"
 
udpdump: udpdump.c
gcc -Wimplicit-function-declaration -Wall -ggdb\
-I$(BASE)/oslib udpdump.c -o udpdump
 
list: list.c
gcc -Wimplicit-function-declaration -Wall -ggdb\
-I$(BASE)/include/trace -I$(BASE)/oslib list.c -o list
 
/advdemos/branches/advdemos/chimera/chimera.h
0,0 → 1,115
/*
* Project: HARTIK (HA-rd R-eal TI-me K-ernel)
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Gerardo Lamastra <gerardo@sssup.it>
*
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://hartik.sssup.it
*/
 
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <kernel/kern.h>
#include <kernel/func.h>
#include <semaphore.h>
#include "modules/sem.h"
#include "modules/hartport.h"
#include <drivers/keyb.h>
 
#include <servo.h>
#include <drivers/udpip.h>
 
/* COM Port Constants */
#define COM_PORT COM1
#define COM_SPEED 115200
 
#define com(i) ((i) / 12) ? COM1 : COM2
#define pin(i) (i) % 12
 
/* Angle bounds */
#define POS_X_MIN 0
#define POS_X_MAX 200
#define POS_Y_MIN -200
#define POS_Y_MAX 200
#define POS_Z_MIN -150
#define POS_Z_MAX 150
 
typedef struct {
int adc_in;
unsigned char pwm;
} LEG_CFG_STATE;
 
typedef struct { /*describe the position of leg*/
int x;
int y;
int z;
} LEG_POS_STATE;
 
typedef struct { /*describe the servo angles*/
int a;
int b;
int c;
} LEG_ANG_STATE;
 
typedef struct {
LEG_CFG_STATE cfg[6];
LEG_ANG_STATE ang[6];
char power;
} HEXAPOD_STATE;
 
/*****************************************/
 
#define EVT_SET_MASK_LEG_ANGLE 0x01
 
#define EVT_STATUS_FREE 0x00
#define EVT_STATUS_WAIT 0x01
#define EVT_STATUS_EXEC 0x02
#define EVT_STATUS_DONE 0x03
 
struct action_event {
 
unsigned char type;
unsigned char status;
struct timespec time;
unsigned char mask;
LEG_ANG_STATE ang; //Servo angle data
unsigned char pwm;
struct action_event *next;
 
};
 
struct action_event *get_first_old_event(struct timespec *time);
 
extern sem_t mx_status;
extern HEXAPOD_STATE status;
 
void init_send(void);
void end_send(void);
 
void init_key(void);
 
/* Calibration */
 
void calibrate_init(void);
void calibrate_step(int step);
int adjust(int angle_sec, int leg, int num);
 
/* Actions */
 
int init_action_event(int number_of_events);
int insert_action_event(struct action_event *e);
int delete_action_event(int event);
struct action_event * get_first_old_event(struct timespec *time);
 
/* Tracer */
 
int trace_init(int buffer_size);
int trace_consumption(int sensor, int value);
int trace_send();
 
/advdemos/branches/advdemos/chimera/action.c
0,0 → 1,161
/*
* Project: S.Ha.R.K.
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "chimera.h"
 
struct action_event *first_action_event = NULL;
struct action_event *action_event_list;
int total_events = 0;
 
int get_free_slot();
 
int init_action_event(int number_of_events) {
 
action_event_list = malloc(number_of_events * sizeof(struct action_event));
memset(action_event_list,0,number_of_events * sizeof(struct action_event));
total_events = number_of_events;
 
if (action_event_list != NULL) return 0;
 
total_events = 0;
return -1;
 
}
 
int insert_action_event(struct action_event *e) {
 
struct action_event *t = first_action_event, *k = NULL;
int free;
 
SYS_FLAGS f;
 
f = kern_fsave();
 
free = get_free_slot();
 
if (free != -1) {
memcpy(&(action_event_list[free]),e,sizeof(struct action_event));
e = &(action_event_list[free]);
 
} else {
 
return -1;
 
}
 
e->status = EVT_STATUS_WAIT;
 
if (!t) {
first_action_event = e;
e->next = NULL;
kern_frestore(f);
return 0;
}
 
while(t) {
if (TIMESPEC_A_LT_B(&e->time,&t->time))
break;
k = t;
t = t->next;
}
 
t = k->next;
k->next = e;
e->next = t;
 
t = first_action_event;
 
kern_frestore(f);
 
return free;
 
}
 
int delete_action_event(int event) {
struct action_event *t = first_action_event;
struct action_event *e = &(action_event_list[event]);
SYS_FLAGS f;
if ((!t || !e) && (e->status != EVT_STATUS_FREE)) return -1;
f = kern_fsave();
if (t == e) {
 
first_action_event = t->next;
e->status = EVT_STATUS_FREE;
kern_frestore(f);
return 0;
 
}
while(t) {
if (t->next == e)
break;
t = t->next;
}
if (t) {
t->next = e->next;
e->status = EVT_STATUS_FREE;
kern_frestore(f);
return 0;
}
kern_frestore(f);
return -1;
}
 
int get_free_slot() {
 
int k = 0;
 
while (k < total_events) {
 
if (action_event_list[k].status == EVT_STATUS_FREE ||
action_event_list[k].status == EVT_STATUS_DONE)
return k;
k++;
 
}
 
return -1;
 
}
 
struct action_event * get_first_old_event(struct timespec *time) {
 
struct action_event *t = first_action_event;
SYS_FLAGS f;
 
if (!t) return NULL;
 
f = kern_fsave();
 
if (TIMESPEC_A_GT_B(time,&(t->time))) {
first_action_event = t->next;
t->status = EVT_STATUS_EXEC;
kern_frestore(f);
return t;
}
 
kern_frestore(f);
return NULL;
 
}
/advdemos/branches/advdemos/slsh/slsh.h
0,0 → 1,204
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
 
/**
------------
CVS : $Id: slsh.h,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
Author: Tomas Lennvall, Date: Feb 2000.
 
This file contains the scheduling module for Slot shifting.
 
Title:
Slot Shifting
 
Task Models Accepted:
STATIC_TASK_MODEL - Periodic Hard tasks that are scheduled by
an off-line scheduler, so that all guarantees regarding precedence, mutex
deadline violation is taken care of. The tasks are in an executione schedule,
that is the order in when they become ready. They have the following fields:
est (earliest start time), wcet and absolute deadline.
HARD_TASK_MODEL - Hard Tasks (Hard aperiodic requests)
wcet field and drel field must be != 0. They are used to set the wcet
and deadline of the tasks.
periodicity field must be APERIODIC
mit field is ignored.
 
SOFT_TASK_MODEL - Soft Tasks (Unspecified tasks)
wcet field must be != 0. periodicity filed must be APERIODIC
period and met filed is ignored.
 
Guest Models Accepted:
NONE - Slot shifting handles all tasks by itself (at this moment).
 
Description:
This module schedules the offline scheduled tasks according to the slot-
shifting paradigm, dividing time into slots of a fixed length and assigning
tasks to execute in those slots. Slot-shifting also keeps track of the free
bandwidth in the schedule by using disjoint intervals and sc (spare capacity).
Each interval has a sc nr that represents the free bandwidth in that interval,
the sc can be used by hard aperiodic tasks, static tasks from later interval or
soft aperiodic tasks. Hard aperiodic tasks are guaranteed an incorporated in
the schedule by reduction of sc before they execute. No guarantee is
performed on the soft aperiodic tasks, they are run when no other task wants
to execute and sc is available.
 
Description:
This module implements the Slot shifting algorithm, by Gerhard Fohler. Slot shifting
schedules off-line scheduled tasks and also handles hard aperiodic requests by the
guarantee alorithm. Slot shifting can also handle soft aperiodic tasks,
called unspecified. That is tasks without a deadline.
 
Exceptions raised:
These exceptions are pclass-dependent...
XDEADLINE_MISS
If a task miss his deadline, the exception is raised.
 
XWCET_VIOLATION
If a task doesn't end the current cycle before if consume the wcet,
an exception is raised, and the task is put in the EDF_WCET_VIOLATED
state. To reactivate it, use EDF_task_activate via task_activate or
manage directly the EDF data structure. Note that the exception is not
handled properly, an XDEADLINE_MISS exeeption will also be raised at
the period end...
 
Restrictions & special features:
- This level doesn't manage the main task.
- At init time we can choose if the level have to activate
. the wcet check
(If a task require more time than declared, it is stopped and put in
the state EDF_WCET_VIOLATED; a XWCET_VIOLATION exception is raised)
. the task guarantee algorithm
(when all task are created the system will check that the task_set
will not use more than the available bandwidth)
- The level use the priority and timespec_priority fields.
- A function to return the used bandwidth of a level is provided.
- The guest tasks don't provide the guest_endcycle function
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __SLSH_H__
#define __SLSH_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
 
#define STATIC_PCLASS 0x0500
 
#define SLSH_LEVELNAME "Slot Shifting"
#define SLSH_LEVEL_CODE 5
#define SLSH_LEVEL_VERSION 1
 
 
 
/* -----------------------------------------------------------------------
STATIC_TASK_MODEL: offline scheduled Tasks
----------------------------------------------------------------------- */
/* Offline-scheduled tasks are hard periodic tasks that have been
scheduled before runtime. All guarantees are made by the off-
line scheduler so the tasks are already guaranteed.
*/
 
typedef struct {
TASK_MODEL t;
TIME est;
TIME wcet;
TIME dabs;
int interval; /* used in slot shifting */
} STATIC_TASK_MODEL;
 
#define static_task_default_model(m) \
task_default_model((m).t,STATIC_PCLASS), \
(m).est = -1, \
(m).dabs = 0, \
(m).wcet = 0, \
(m).interval = -1;
#define static_task_def_level(m,l) task_def_level((m).t,l)
#define static_task_def_arg(m,a) task_def_arg((m).t,a)
#define static_task_def_stack(m,s) task_def_stack((m).t,s)
#define static_task_def_group(m,g) task_def_group((m).t,g)
#define static_task_def_usemath(m) task_def_usemath((m).t)
#define static_task_def_system(m) task_def_system((m).t)
#define static_task_def_nokill(m) task_def_nokill((m).t)
#define static_task_def_ctrl_jet(m) task_def_ctrl_jet((m).t)
#define static_task_def_est(m,p) (m).est = (p)
#define static_task_def_dabs(m,d) (m).dabs = (d)
#define static_task_def_wcet(m,w) (m).wcet = (w)
#define static_task_def_interval(m,i) (m).interval = (i)
#define static_task_def_trace(m) task_def_trace((m).t)
#define static_task_def_notrace(m) task_def_notrace((m).t)
 
 
 
 
/*#define min(a, b) ((a) < (b) ? (a) : (b))*/
 
#define TIME2TIMESPEC(T, TS) \
( \
((TS).tv_sec = ((T)/1000000)), \
((TS).tv_nsec = (((T)%1000000) * 1000)), \
(TS) \
)
 
/* define the interval struct */
typedef struct {
int start; /* start of interval */
int end; /* end of interval */
int length; /* Length of interval */
int maxt; /* maximum execution time in interval */
int sc; /* spare capacity in interval */
} SLSH_interval;
 
/*+ Registration function: */
LEVEL SLSH_register_level();
 
void SLSH_set_interval(LEVEL l, int start, int end, int maxt);
void SLSH_set_variables(LEVEL l, TIME length);
 
#endif
 
/advdemos/branches/advdemos/slsh/slsh.c
0,0 → 1,750
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: slsh.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
This file contains the scheduling module for Slot-Shifting.
 
Read slsh.h for further details.
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#include "slsh.h"
#include <ll/stdio.h>
#include <ll/stdlib.h>
#include <ll/string.h>
#include <ll/math.h> /* for ceil(...) */
#include <ll/ll.h> /* for memcpy(...) */
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
//#define eslsh_printf kern_printf
#define slsh_printf printk
 
/* Keeps information about static and guaranteed tasks */
typedef struct {
int est;
int dabs;
int interval;
} SLSH_task;
 
/*+ Status used in the level +*/
#define SLSH_READY MODULE_STATUS_BASE
#define SLSH_WAIT MODULE_STATUS_BASE + 1
#define SLSH_IDLE MODULE_STATUS_BASE + 2
#define SLSH_WCET_VIOLATED MODULE_STATUS_BASE + 3
 
/*+ defines +*/
#define MAX_INTERVALS 1000 /* 1000 intervals is max, for now */
 
/******+ the level redefinition for the SLOT SHIFT level +*******/
typedef struct {
level_des l; /*+ the standard level descriptor+*/
 
/* task lists */
SLSH_task tasks[MAX_PROC]; /* est and dl's for static and guaranteed task */
IQUEUE idle_statics; /* finished static tasks */
IQUEUE unspecified; /* tasks with only a wcet */
/* the Intervals list */
SLSH_interval intervals[MAX_INTERVALS];
int current; /* current interval */
int last; /* last interval */
int slot; /* slot shifting time */
TIME slot_length; /* slothlength in real system time*/
int LCM; /* length (in slots) of ofline schedule */
int slot_event; /* save the event */
} SLSH_level_des;
 
 
/* check if some tasks are ready, return 0 if ready, -1 otherwise */
static int SLSH_R(SLSH_task* tasks)
{
int s;
 
/* for all static tasks */
for(s = 0; tasks[s].est != -1; ++s)
{
if(proc_table[s].status == SLSH_READY)
return 0;
}
return -1;
}
 
/* check if unspecified exists, return 0 if it exists, -1 otherwise */
static int SLSH_T(IQUEUE *unspecified)
{
if(!iq_isempty(unspecified))
return 0;
else
return -1;
}
 
/* return the sc in an interval */
static int SLSH_sc(SLSH_interval* intervals, int i)
{
return intervals[i].sc;
}
/* return a static task from current interval or a guaranted task */
static PID SLSH_staticOrGuaranteed(SLSH_level_des* lev)
{
int lowest_dl = 0; /* lowest dl found */
PID pid = 0; /* static or guaranteed task */
int t;
 
/* Decide according to EDF, go through all static & guaranteed tasks */
for(t = 0; t < MAX_PROC; ++t)
{
/* static tasks */
if(proc_table[t].pclass == STATIC_PCLASS)
{
/* static task must belong to current interval */
if(lev->tasks[t].interval == lev->current)
{
/* only ready tasks */
if(proc_table[t].status == SLSH_READY)
{
/* a new lower dl was found */
if(lev->tasks[t].dabs < lowest_dl)
{
lowest_dl = lev->tasks[t].dabs;
pid = t;
}
}
}
} /* guaranteed tasks */
else if(proc_table[t].pclass == HARD_PCLASS)
{
/* only ready tasks */
if(proc_table[t].status == SLSH_READY)
{
/* a new lower dl was found */
if(lev->tasks[t].dabs < lowest_dl)
{
lowest_dl = lev->tasks[t].dabs;
pid = t;
}
}
}
}/* for all tasks */
return pid;
}
 
/* return a static task among the candidates, all ready statics */
static PID SLSH_candidates(SLSH_task* tasks)
{
int lowest_dl = 0;
PID pid = -1;
int t;
 
/* Use the EDL algorithm again to decide which task to run */
for(t = 0; t < MAX_PROC; ++t)
{
/* only static tasks */
if(proc_table[t].pclass == STATIC_PCLASS)
{
/* only ready tasks */
if(proc_table[t].status == SLSH_READY)
{
/* a new lower dl was found */
if(tasks[t].dabs < lowest_dl)
{
lowest_dl = tasks[t].dabs;
pid = t;
}
}/* all ready tasks */
}/* all static tasks */
}/* for all tasks */
return pid;
}
 
/* decrease the sc in a interval by amount */
void SLSH_decSc(SLSH_interval* intervals, int i, int amount)
{
intervals[i].sc -= amount;
}
 
void SLSH_incSc(SLSH_interval* intervals, int i, int amount)
{
intervals[i].sc += amount;
}
 
/* swap the sc between intervals, also consider intervals with negative sc */
void SLSH_swapSc(SLSH_interval* intervals, int current, int task_interval)
{
/* decrease the sc in the current interval */
SLSH_decSc(intervals, current, 1);
/* update the other interval(s) */
if(intervals[task_interval].sc < 0) /* negative sc */
{
/* special case, increase next interval sc by 1 and also current interval (borrowing) */
if(task_interval == current + 1)
{
SLSH_incSc(intervals, task_interval, 1);
SLSH_incSc(intervals, current, 1);
}
else /* increase every interval sc that is negative between current and task_interval */
{
while(task_interval > current && intervals[task_interval].sc < 0)
{
SLSH_incSc(intervals, task_interval, 1);
task_interval--;
}
}
}
else /* ordinary swapping */
SLSH_incSc(intervals, task_interval, 1);
}
 
/* The scheduler, decides which task to run. */
static PID SLSH_public_scheduler(LEVEL l)
{
SLSH_level_des* lev = (SLSH_level_des *)(level_table[l]);
PID pid;
/* The scheduler choses among static, guaranteed (hard aperiodic) and
unspecified (soft aperiodic) tasks */
/* no ready tasks and no sc, execute idle task */
if(SLSH_R(lev->tasks) == 0 && SLSH_sc(lev->intervals, lev->current) == 0)
return NIL;
/* must execute a static from current intervall or a guaranteed task */
else if(SLSH_R(lev->tasks) > 0 && SLSH_sc(lev->intervals, lev->current) == 0)
return SLSH_staticOrGuaranteed(lev);
/* sc available... */
else if(SLSH_R(lev->tasks) > 0 && SLSH_sc(lev->intervals, lev->current) > 0)
{
/* If unspecified exist, execute it according to FIFO order */
if(SLSH_T(&lev->unspecified) == 0)
{
SLSH_decSc(lev->intervals, lev->current, 1); /* decrease sc by 1 */
return iq_getfirst(&lev->unspecified);
}
else /* No unspecified, execute task from candidates (statics) */
{
pid = SLSH_candidates(lev->tasks);
 
/* sc needs to be swapped */
if(lev->tasks[pid].interval != lev->current)
SLSH_swapSc(lev->intervals, lev->tasks[pid].interval, lev->current);
return pid;
}
}
 
kern_printf("(SLSH s)");
return NIL;
}
 
/* not used, slot-shifting handles all guarantees itself, it handles all bandwidth */
static int SLSH_public_guarantee(LEVEL l, bandwidth_t *freebandwidth)
{
*freebandwidth = 0;
return 1;
}
 
/* get the interval that x is in */
static int SLSH_getInterval(SLSH_interval* intervals, int x, int last)
{
int i;
 
/* search through the intervals */
for(i = 0; i <= last; ++i)
{
/* I is in the interval where start is smaller or equal and end is bigger */
if(intervals[i].start <= x && x < intervals[i].end)
return i;
}
return -1;
}
 
/* get the start of the interval I */
static int SLSH_intervalStart(SLSH_interval* intervals, int I)
{
return intervals[I].start;
}
 
/* split interval I into two parts, slow because of copying. OBS!!! no check if there is
enough space in the intervals array */
static void SLSH_splitInterval(SLSH_level_des* lev, int I, int dabs)
{
SLSH_interval left_interval;
int i;
 
 
lev->last++;
/* move every interval above and including I */
for(i = lev->last; i > I; --i)
memcpy(&lev->intervals[i], &lev->intervals[i - 1], sizeof(SLSH_interval));
/* Left interval start, end and length */
left_interval.start = lev->intervals[I].start;
left_interval.end = dabs;
left_interval.length = left_interval.end - left_interval.start;
/* Right interval (uses old interval struct) start and length end remains as the old value */
lev->intervals[I + 1].start = dabs;
lev->intervals[I + 1].length = lev->intervals[I + 1].end - lev->intervals[I + 1].start;
/* check if sc still exists in the right interval */
if(lev->intervals[I + 1].length - lev->intervals[I + 1].maxt > 0)
{
lev->intervals[I + 1].sc = lev->intervals[I + 1].length - lev->intervals[I + 1].maxt;
left_interval.sc = left_interval.length; /* the whole interval is free, for now... */
}
else /* no sc in the right interval */
{
lev->intervals[I + 1].maxt = lev->intervals[I + 1].length;
left_interval.sc = lev->intervals[I + 1].sc; /* all sc in left interval */
lev->intervals[I + 1].sc = 0;
}
/* insert the new interval */
memcpy(&lev->intervals[I], &left_interval, sizeof(SLSH_interval));
}
 
/* Reduce the sc from back to front by the wcet amount, interval splitting may be neccesary */
static void SLSH_updateSc(SLSH_level_des* lev, HARD_TASK_MODEL* h)
{
int dabs = ceil((lev->slot + h->drel)/lev->slot_length); /* absolute deadline of request */
int dabs_interval = SLSH_getInterval(lev->intervals, dabs, lev->last); /* interval where dabs is */
int C = ceil(h->wcet/lev->slot_length); /* amount of sc to reduce */
int sc = 0;
int i;
 
/* check if interval splitting is neccesary */
if(lev->intervals[dabs_interval].end != dabs)
SLSH_splitInterval(lev, dabs_interval, dabs);
/* decrease sc in all intervals that are neccesary from dabs_interval o current */
for(i = dabs_interval; i >= lev->current && C > 0; --i)
{
if((sc = SLSH_sc(lev->intervals, i)) >= 0) /* only decrease where sc exists */
{
if(sc > C) /* the last sc dec */
{
SLSH_decSc(lev->intervals, i, C);
C = 0;
}
else /* to little sc in this interval, decrease it to 0 */
{
C -= SLSH_sc(lev->intervals, i);
SLSH_decSc(lev->intervals, i, SLSH_sc(lev->intervals, i));
}
}
}/* for all intervals */
}
 
/* the guarantee algorithm for hard aperiodic requests */
static int SLSH_guarantee(SLSH_level_des* lev, HARD_TASK_MODEL* h)
{
int total_sc = 0;
int temp, i;
int dabs = ceil((lev->slot + h->drel)/lev->slot_length); /* absolute deadline of request */
int dabs_interval = SLSH_getInterval(lev->intervals, dabs, lev->last); /* interval where dabs is */
/* check if the sc up until request deadline is >= request wcet */
/* 1. the sc of the current interal */
total_sc = SLSH_sc(lev->intervals, lev->current);
 
/* 2. the sc for all whole intervals between current and the interval
with the request deadline */
for(i = (lev->current) + 1; i < dabs_interval; ++i)
{
if((temp = SLSH_sc(lev->intervals, i)) > 0)
total_sc += temp;
}
/* 3. the min of sc or the execution need in the last interval */
total_sc += min(SLSH_sc(lev->intervals, dabs_interval),
dabs - SLSH_intervalStart(lev->intervals,
dabs_interval));
 
if(total_sc >= h->wcet)
{ /* update the sc in the intervals from back to front */
SLSH_updateSc(lev, h);
return 0;
}
else
return -1;
}
 
/* check if task model is accepted and store nessecary parameters */
static int SLSH_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
STATIC_TASK_MODEL* s;
HARD_TASK_MODEL* h;
SOFT_TASK_MODEL* u;
 
 
/* Check the models */
switch(m->pclass)
{
case STATIC_PCLASS: /* offline scheduled tasks */
break;
case HARD_PCLASS: /* hard aperiodic tasks */
h = (HARD_TASK_MODEL *) m;
if (h->drel == 0 || h->wcet == 0) /* must be set */
return -1;
break;
case SOFT_PCLASS: /* soft aperiodic tasks */
u = (SOFT_TASK_MODEL *) m;
if(u->wcet == 0) /* must be set */
return -1;
break;
default:
return -1;
}
 
 
/* if the SLSH_task_create is called, then the pclass must be a
valid pclass. Slot-shifting accepts STATIC_TASK, HARD_TASK
and SOFT_TASK models with some restrictions */
 
/* est, dl and wcet is saved in slotlengths */
switch(m->pclass)
{
case STATIC_PCLASS: /* offline scheduled tasks */
s = (STATIC_TASK_MODEL *) m;
lev->tasks[p].est = ceil(s->est/lev->slot_length);
lev->tasks[p].dabs = ceil(s->dabs/lev->slot_length);
lev->tasks[p].interval = s->interval;
proc_table[p].avail_time = s->wcet;
proc_table[p].wcet = s->wcet;
break;
case HARD_PCLASS: /* hard aperiodic tasks */
h = (HARD_TASK_MODEL *) m;
if(SLSH_guarantee(lev, h) == 0)
{
/* convert drel to dabs */
lev->tasks[p].dabs = ceil((lev->slot + h->drel)/lev->slot_length);
proc_table[p].avail_time = h->wcet;
proc_table[p].wcet = h->wcet;
}
else /* task not guaranteed */
return -1;
break;
case SOFT_PCLASS:
u = (SOFT_TASK_MODEL *) m;
proc_table[p].avail_time = u->wcet;
proc_table[p].wcet = u->wcet;
iq_insertlast(p, &lev->unspecified); /* respect FIFO order */
break;
default: /* a task model not supported */
return -1;
}
/* enable wcet check in the kernel */
proc_table[p].control |= CONTROL_CAP;
return 0;
}
 
/************* The slot end event handler *************/
static void SLSH_slot_end(void* p)
{
SLSH_level_des* lev = (SLSH_level_des *) p;
PID pid;
int i;
/* increase slot "time" by 1 */
if(lev->slot < lev->LCM)
{
lev->slot++;
/* check if new statics are ready */
for(i = 0; lev->tasks[i].interval != -1; ++i)
{
if(lev->tasks[i].est <= lev->slot && proc_table[i].status == SLSH_WAIT)
proc_table[i].status = SLSH_READY;
}
/* check if current (interval) needs updating */
if(lev->current < SLSH_getInterval(lev->intervals, lev->slot, lev->last))
lev->current++;
}
else /* restart from the beginning of the offline schedule */
{
lev->slot = 0;
while((pid = iq_getfirst(&lev->idle_statics)) != NIL)
{
if(lev->tasks[pid].est <= lev->slot)
proc_table[pid].status = SLSH_READY;
else
proc_table[pid].status = SLSH_WAIT;
}
}
 
/* call for a rescheduling, reset event flag and increase slot by 1 */
lev->slot_event = -1;
kern_printf("*");
event_need_reschedule();
}
 
/* when a task becomes executing (EXE status) */
static void SLSH_public_dispatch(LEVEL l, PID pid, int nostop)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
struct timespec t;
 
/* the task state is set EXE by the scheduler()
we extract the task from the unspecified queue.
NB: we can't assume that p is the first task in the queue!!! */
if(proc_table[pid].pclass == SOFT_PCLASS)
iq_extract(pid, &lev->unspecified);
 
/* also start the timer for one slot length */
lev->slot_event = kern_event_post(&TIME2TIMESPEC(lev->slot_length, t),
SLSH_slot_end, (void*) lev);
}
 
/* called when task is moved from EXE status */
static void SLSH_public_epilogue(LEVEL l, PID pid)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
 
/* check if the wcet is finished... */
if (proc_table[pid].avail_time <= 0)
{
/* if it is, raise a XWCET_VIOLATION exception */
kern_raise(XWCET_VIOLATION, pid);
proc_table[pid].status = SLSH_WCET_VIOLATED;
}
else /* the end of a slot. the task returns into the ready queue... */
{
if(proc_table[pid].pclass == SOFT_PCLASS)
iq_insertfirst(pid,&lev->unspecified);
proc_table[pid].status = SLSH_READY;
}
}
 
/* when task go from SLEEP to SLSH_READY or SLSH_WAIT */
static void SLSH_public_activate(LEVEL l, PID pid)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
WORD type = proc_table[pid].pclass;
 
/* Test if we are trying to activate a non sleeping task */
/* Ignore this; the task is already active */
if (proc_table[pid].status != SLEEP && proc_table[pid].status != SLSH_WCET_VIOLATED)
return;
 
/* make task ready or waiting, dependong on slot (the time) for static tasks only*/
if(type == STATIC_PCLASS && lev->tasks[pid].est <= lev->slot)
proc_table[pid].status = SLSH_READY;
else
proc_table[pid].status = SLSH_WAIT;
if(type == HARD_PCLASS)
proc_table[pid].status = SLSH_READY;
/* insert unspecified tasks in QQUEUE and make it ready */
if(type == SOFT_PCLASS)
{
iq_insertlast(pid ,&lev->unspecified);
proc_table[pid].status = SLSH_READY;
}
}
 
/* when a task i returned to module from a semaphore, mutex ... */
static void SLSH_public_unblock(LEVEL l, PID pid)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
 
/* change staus of task */
proc_table[pid].status = SLSH_READY;
if(proc_table[pid].pclass == SOFT_PCLASS)
iq_insertfirst(pid ,&lev->unspecified);
}
 
/* when a semaphore, mutex ... taskes a task from module */
static void SLSH_public_block(LEVEL l, PID pid)
{
/* Extract the running task from the level
. we have already extract it from the ready queue at the dispatch time.
. the capacity event have to be removed by the generic kernel
. the wcet don't need modification...
. the state of the task is set by the calling function
. the deadline must remain...
 
So, we do nothing!!!
*/
}
 
/* the task has finihed its wcet, kill task (dont kill static tasks) */
static void SLSH_public_end(LEVEL l, PID pid)
{
SLSH_level_des *lev = (SLSH_level_des *)(level_table[l]);
 
if(proc_table[pid].pclass == SOFT_PCLASS)
{
if (proc_table[pid].status == SLSH_READY)
iq_extract(pid, &lev->unspecified);
}
else if(proc_table[pid].pclass == HARD_PCLASS)
{
if (proc_table[pid].status == SLSH_READY)
lev->tasks[pid].dabs = 0;
}
/* static tasks: put them in idle QUEUE, reset status and avail_time */
else if(proc_table[pid].pclass == STATIC_PCLASS)
{
proc_table[pid].avail_time = proc_table[pid].wcet;
proc_table[pid].status = SLSH_IDLE;
iq_priority_insert(pid, &lev->idle_statics);
}
proc_table[pid].status = FREE;
}
 
/* called when a task should sleep but not execute for awhile, mabe a mode change */
//static void SLSH_task_sleep(LEVEL l, PID pid)
//{
//
// /* the task has terminated his job before it consume the wcet. All OK! */
// proc_table[pid].status = SLEEP;
//
// /* we reset the capacity counters... only for static tasks */
// if (proc_table[pid].pclass == STATIC_PCLASS)
// proc_table[pid].avail_time = proc_table[pid].wcet;
//
//}
 
 
/** Guest Functions, slot shifing accepts no guests, so all generates exceptions **/
 
/******* Registration functions *******/
 
/*+ Registration function: */
LEVEL SLSH_register_level()
{
LEVEL l; /* the level that we register */
SLSH_level_des *lev; /* for readableness only */
PID i; /* a counter */
kern_printf("SLSH_register_level\n");
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(SLSH_level_des));
lev = (SLSH_level_des *)level_table[l];
printk(" lev=%d\n",(int)lev);
/* fill the standard descriptor */
lev->l.public_scheduler = SLSH_public_scheduler;
lev->l.public_guarantee = SLSH_public_guarantee;
lev->l.public_create = SLSH_public_create;
lev->l.public_end = SLSH_public_end;
lev->l.public_dispatch = SLSH_public_dispatch;
lev->l.public_epilogue = SLSH_public_epilogue;
lev->l.public_activate = SLSH_public_activate;
lev->l.public_unblock = SLSH_public_unblock;
lev->l.public_block = SLSH_public_block;
/* fill the SLSH descriptor part */
for(i = 0; i < MAX_PROC; i++)
{
lev->tasks[i].est = -1;
lev->tasks[i].dabs = 0;
lev->tasks[i].interval = -1;
}
for(i = 0; i < MAX_INTERVALS; i++)
{
lev->intervals[i].start = -1;
lev->intervals[i].end = -1;
lev->intervals[i].length = 0;
lev->intervals[i].maxt = 0;
lev->intervals[i].sc = 0;
}
 
lev->current = 0;
lev->last = NIL;
lev->slot = 0;
lev->slot_length = 0;
lev->slot_event = -1;
 
return l;
}
 
 
void SLSH_set_interval(LEVEL l, int start, int end, int maxt)
{
SLSH_level_des* lev = (SLSH_level_des *)(level_table[l]);
static int i = -1;
i++;
lev->intervals[i].start = start;
lev->intervals[i].end = end;
lev->intervals[i].length = end - start;
lev->intervals[i].maxt = maxt;
lev->intervals[i].sc = lev->intervals[i].length - maxt;
lev->last = i;
}
 
void SLSH_set_variables(LEVEL l, TIME length)
{
SLSH_level_des* lev = (SLSH_level_des *)(level_table[l]);
lev->slot_length = length;
}
/advdemos/branches/advdemos/slsh/slshtest.c
0,0 → 1,173
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: slshtest.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
Slot shifting test
**/
 
/*
* Copyright (C) 2000 Paolo Gai and Tomas Lennvall
*
* This program 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.
*
* This program 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
*
*/
 
#include <kernel/config.h>
#include "kernel/kern.h"
#include "slsh.h"
#include "drivers/keyb.h"
 
/* a slot length of 100 ms */
#define SLOT_LENGTH 100000
 
 
TASK static1(void)
{
int i = 0;
 
kern_printf("Static1\n");
while(sys_gettime(NULL) < 10000) i++;
 
return 0;
}
 
TASK static2(void)
{
int i = 0;
kern_printf("Static2\n");
while(sys_gettime(NULL) < 10000) i++;
 
return 0;
}
 
 
TASK static3(void)
{
kern_printf("Static3\n");
 
return 0;
}
 
void my_end(KEY_EVT *e)
{
sys_end();
}
 
int main(int argc, char** argv)
{
STATIC_TASK_MODEL s;
// HARD_TASK_MODEL h_aper;
// SOFT_TASK_MODEL u;
PID p1,p2,p3;
struct timespec x;
KEY_EVT emerg;
 
kern_cli();
x.tv_sec=5;
kern_event_post(&x,(void (*)(void *))sys_end,NULL);
kern_sti();
 
//keyb_set_map(itaMap);
emerg.ascii = 'x';
emerg.scan = KEY_X;
emerg.flag = ALTL_BIT;
keyb_hook(emerg,my_end);
 
/* set som variables in the scheduling level */
SLSH_set_interval(0, 0, 8, 5);
SLSH_set_interval(0, 8, 17, 7);
SLSH_set_interval(0, 17, 20, 1);
 
SLSH_set_variables(0, SLOT_LENGTH);
static_task_default_model(s);
static_task_def_group(s, 1);
/* define time i ms */
/* static1 task */
static_task_def_est(s, 0);
static_task_def_dabs(s, 800000);
static_task_def_wcet(s, 500000);
static_task_def_interval(s, 0);
 
kern_printf("In main, before task creation\n");
 
p1 = task_create("Static 1", static1, &s, NULL);
if(p1 == NIL)
kern_printf("Cannot create: Static1!\n");
/* Static2 task */
static_task_def_est(s, 800000);
static_task_def_dabs(s, 1700000);
static_task_def_wcet(s, 700000);
static_task_def_interval(s, 1);
p2 = task_create("Static 2", static2, &s, NULL);
if(p2 == NIL)
kern_printf("Cannot create: Static2!\n");
 
/* Static3 task */
static_task_def_est(s, 1700000);
static_task_def_dabs(s, 2000000);
static_task_def_wcet(s, 100000);
static_task_def_interval(s, 2);
 
p3 = task_create("Static3", static3, &s, NULL);
if(p3 == NIL)
kern_printf("Cannot create: Static3!\n");
 
 
/* End task */
/*hard_task_default_model(h_aper);
hard_task_def_wcet(h_aper, 100000);
*/
kern_printf("After task creation\n");
 
group_activate(1);
 
return 0;
}
/advdemos/branches/advdemos/slsh/readme.txt
0,0 → 1,6
This Example has been made by Tomas Lenvall.
 
There is not a lot of documentation available, so if you have problems please
send an e-mail to Tomas ( mailto:tlv@mdh.se )
 
Paolo
/advdemos/branches/advdemos/slsh/makefile
0,0 → 1,16
#
#
#
 
ifndef BASE
BASE=../..
endif
 
include $(BASE)/config/config.mk
 
PROGS=slshtest
 
include $(BASE)/config/example.mk
 
slshtest:
make -f $(SUBMAKE) APP=slshtest INIT= OTHEROBJS="slshinit.o slsh.o" OTHERINCL= SHARKOPT=__OLDCHAR__
/advdemos/branches/advdemos/slsh/slshinit.c
0,0 → 1,117
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: slshinit.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
System initialization file
 
The tick is set to TICK ms.
 
This file contains the 2 functions needed to initialize the system.
 
These functions register the following levels:
 
a Slot Shifting level
a Dummy level
 
It can accept these task models:
 
STATIC_TASK_MODEL
HARD_TASK_MODEL(aperiodic)
SOFT_TASK_MODEL
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
 
#include "kernel/kern.h"
#include "slsh.h"
#include "modules/rr2.h"
#include "modules/sem.h"
#include "modules/hartport.h"
#include "drivers/keyb.h"
#include "modules/dummy.h"
 
/*+ sysyem tick in us +*/
#define TICK 300
 
/* define RR tick in us*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
SLSH_register_level();
RR2_register_level(RRTICK, RR2_MAIN_YES, mb);
dummy_register_level();
 
SEM_register_module();
 
return TICK;
}
 
NRT_TASK_MODEL nrt;
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS k = BASE_KEYB;
 
nrt_task_default_model(nrt);
keyb_def_task(k,&nrt);
 
 
 
HARTPORT_init();
 
KEYB_init(NULL);
 
__call_main__(mb);
 
return 0;
}
 
 
/advdemos/branches/advdemos/block/idetest0.c
0,0 → 1,15
/*
*
*
*
*/
 
#include <fs/bdev.h>
 
#include "common.h"
 
int main(int argc,char *argv[])
{
showmessage("Have ide devices been found?\n");
return 0;
}
/advdemos/branches/advdemos/block/idetest1.c
0,0 → 1,20
/*
*
*
*
*/
 
#include <fs/bdev.h>
 
#include "common.h"
 
int main(int argc,char *argv[])
{
 
showmessage("This test try to identify the partions of all hard disks\n");
bdev_dump_names();
 
waitend();
return 0;
}
/advdemos/branches/advdemos/block/idetest2.c
0,0 → 1,77
/*
*
*
*
*/
 
#include <ll/i386/cons.h>
#include <drivers/keyb.h>
 
#include <fs/bdevinit.h>
#include <fs/bdev.h>
 
#include <string.h>
 
#include "common.h"
 
#define DISKDEVICE "ide/hda1"
 
__uint8_t buffer[2048] __attribute__ ((aligned (4)));
__dev_t dev;
 
extern char *ide_error_msg[];
 
int main(int argc,char *argv[])
{
__blkcnt_t blk;
int res;
int c;
 
showmessage("This test try to read some blocks from first hard disk\n");
 
dev=bdev_find_byname(DISKDEVICE);
if (dev<0) {
cprintf("Can't find device to operate with\n");
return -1;
}
cprintf("Using device %s (dev=%04x)\n",DISKDEVICE,dev);
 
blk=0;
for (;;) {
cprintf("Commands: x-exit r-read n-next block p-prev block\n");
c = keyb_getchar();
switch(c) {
case 'x':
return 0;
 
case 'n':
blk++;
cprintf("Block %li\n",(long)blk);
break;
 
case 'p':
if (blk>=0) blk--;
cprintf("Block %li\n",(long)blk);
break;
case 'r':
cprintf("Reading block %li...\n",(long)blk);
memset(buffer,0xff,sizeof(buffer));
res=bdev_read(dev,blk,buffer);
cprintf("Result %i\n",res);
//cprintf("Soft reset done %i\n",ide[0].errors);
if (res!=0) {
cprintf(" %s\n",(char*)ide_error_msg[-res]);
}
debug_dump_buffer(buffer,64);
break;
 
default:
cprintf("Invalid command!\n");
break;
}
cprintf("\n");
}
return 0;
}
/advdemos/branches/advdemos/block/idetest3.c
0,0 → 1,66
/*
*
*
*
*/
 
#include <ll/i386/cons.h>
#include <drivers/keyb.h>
 
#include <fs/bdevinit.h>
#include <fs/bdev.h>
 
#include <string.h>
 
#include "common.h"
 
#define DISKDEVICE "ide/hda1"
#define BLOCKNUMBER 58549
 
__uint8_t buffer[2048] __attribute__ ((aligned (4)));
 
extern char *ide_error_msg[];
 
int main(int argc,char *argv[])
{
__dev_t dev;
__blkcnt_t blk;
int res;
// int c;
 
showmessage("This test tries to read a block from the first hard disk\n"
"and then it tries to write it to disk\n"
"Press [CTRL-C] to abort...");
dev=bdev_find_byname(DISKDEVICE);
if ((int)dev<0) {
cprintf("Can't find device to operate with\n");
cprintf("%s not present!\n",DISKDEVICE);
return -1;
}
cprintf("Using device %s (dev=%04x)\n",DISKDEVICE,dev);
blk=BLOCKNUMBER;
 
cprintf("Reading block %li...\n",(long)blk);
memset(buffer,0xff,sizeof(buffer));
res=bdev_read(dev,blk,buffer);
cprintf("Result %i\n",res);
//cprintf("Soft reset done %i\n",ide[0].errors);
if (res!=0) {
cprintf(" %s\n",(char*)ide_error_msg[-res]);
return -1;
}
debug_dump_buffer(buffer,64);
 
cprintf("Writing block %li...\n",(long)blk);
res=bdev_write(dev,blk,buffer);
cprintf("Result %i\n",res);
//cprintf("Soft reset done %i\n",ide[0].errors);
if (res!=0) {
cprintf(" %s\n",(char*)ide_error_msg[-res]);
}
 
waitend();
return 0;
}
/advdemos/branches/advdemos/block/idelin.c
0,0 → 1,71
/*
*
*
*
*/
 
#include <ll/i386/cons.h>
#include <kernel/func.h>
 
#include <fs/bdevinit.h>
#include <fs/bdev.h>
 
#include <stdlib.h>
#include <string.h>
 
#include "common.h"
 
#define DISKDEVICE "ide/hda"
 
#define TEST_MB 16
 
#define NUMBLOCK (TEST_MB*1024l*1024l/512l)
 
__dev_t dev;
 
__uint8_t buffer[2048];
 
int main(int argc,char *argv[])
{
__blkcnt_t blk;
int res;
int errors;
TIME sttime,etime;
 
showmessage("\n"
"This test read data from first hard disk to test\n"
"disk throughtput.\n"
"Remeber that the reads are made block by block so\n"
"don't worry if you see a low throughtput.\n"
);
dev=bdev_find_byname(DISKDEVICE);
if (dev<0) {
cprintf("\nCan't find device to operate with\n");
return -1;
}
cprintf("\nUsing device %s (dev=%04x)\n",DISKDEVICE,dev);
 
cprintf("Please wait (reading %i MB linearly?!?)...",TEST_MB);
 
sttime=sys_gettime(NULL);
errors=0;
for (blk=0;blk<NUMBLOCK;blk++) {
res=bdev_read(dev,blk,buffer);
//res=bdev_seek(dev,blk);
if (res!=0) errors++;
}
etime=sys_gettime(NULL)-sttime;
 
cprintf("\nDone\n\n");
cprintf("elapse time : %li sec %li msec\n",
etime/1000000l,
(etime/1000l)%1000l);
cprintf("throughtput : %6.3f MB/s\n",
NUMBLOCK*512.0/1024.0/1024.0/etime*1000000.0);
//cprintf("soft reset made: %i\n",ide[0].errors);
cprintf("errors : %i\n",errors);
cprintf("\n");
return 0;
}
/advdemos/branches/advdemos/block/idernd.c
0,0 → 1,68
/*
*
*
*
*/
 
#include <ll/i386/cons.h>
#include <kernel/func.h>
 
#include <fs/bdevinit.h>
#include <fs/bdev.h>
 
#include <stdlib.h>
#include <string.h>
 
#include "common.h"
 
#define DISKDEVICE "ide/hda1"
 
#define NUMBLOCK 1000
 
__dev_t dev;
__uint8_t buffer[2048];
 
int main(int argc,char *argv[])
{
__blkcnt_t blk;
int res;
int errors;
TIME sttime,etime;
showmessage("\n"
"This test read RAMDOMLY data from first hard disk to test\n"
"disk throughtput.\n"
"Remeber that the reads are made RANDOMLY block by block so\n"
"don't worry if you see a VERY low throughtput.\n"
);
srand(7);
 
dev=bdev_find_byname(DISKDEVICE);
if (dev<0) {
cprintf("\nCan't find device to operate with\n");
return -1;
}
cprintf("\nUsing device %s (dev=%04x)\n",DISKDEVICE,dev);
 
cprintf("Please wait (reading %i KB ramdomly)...",NUMBLOCK/2);
 
sttime=sys_gettime(NULL);
errors=0;
for (blk=0;blk<NUMBLOCK;blk++) {
res=bdev_read(dev,rand()%5000,buffer);
if (res!=0) errors++;
}
etime=sys_gettime(NULL)-sttime;
 
cprintf("\nDone\n\n");
cprintf("elapse time : %li sec %li msec\n",
etime/1000000l,
(etime/1000l)%1000l);
cprintf("throughtput : %6.3f KB/s\n",
NUMBLOCK*512.0/1024.0/etime*1000000.0);
//cprintf("soft reset made: %i\n",ide[0].errors);
cprintf("errors : %i\n",errors);
cprintf("\n");
return 0;
}
/advdemos/branches/advdemos/block/common.c
0,0 → 1,74
 
#include <kernel/func.h>
 
#include <fs/bdevinit.h>
#include <fs/fsinit.h>
#include <fs/bdev.h>
 
#include <drivers/keyb.h>
 
#include <sys/mount.h>
 
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
 
/* -- */
 
int __register_sub_init(void)
{
return 0;
}
 
/* -- */
 
int __bdev_sub_init(void)
{
BDEV_PARMS bdev=BASE_BDEV;
bdev_def_showinfo(bdev,TRUE);
bdev_init(&bdev);
 
return 0;
}
 
/* -- */
 
void ctrlc_exit(KEY_EVT *k)
{
cprintf("CTRL-C pressed!\n");
sys_end();
}
 
/* -- */
 
void showmessage(char *s)
{
cputs(s);
cprintf("Press [x] to begin...");
while (keyb_getchar()!='x');
cprintf("\n");
}
 
void waitend(void)
{
int c;
cprintf("Press [x] to exit...");
while ((c=keyb_getchar())!='x');
cprintf("\n");
}
 
/* -- */
 
void debug_dump_buffer(char *buf, int size)
{
int i;
for (i=0;i<size;i++) {
if (i%16==0) {
if (i!=0) cprintf("\n");
cprintf("%04x: ",i);
}
cprintf("%02x ",(unsigned char)*(buf+i));
}
cprintf("\n");
}
/advdemos/branches/advdemos/block/makefile
0,0 → 1,34
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS=idetest0 idetest1 idetest2 idetest3 idelin idernd idetx430
 
include $(BASE)/config/example.mk
 
#
#
#
 
idetest0:
make -f $(SUBMAKE) BASE=$(BASE) APP=idetest0 OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
 
idetest1:
make -f $(SUBMAKE) BASE=$(BASE) APP=idetest1 OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
 
idetest2:
make -f $(SUBMAKE) BASE=$(BASE) APP=idetest2 OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
 
idetest3:
make -f $(SUBMAKE) BASE=$(BASE) APP=idetest3 OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
 
idelin:
make -f $(SUBMAKE) BASE=$(BASE) APP=idelin OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
 
idernd:
make -f $(SUBMAKE) BASE=$(BASE) APP=idernd OTHEROBJS="common.o initblk.o" SHARKOPT=__OLDCHAR__
/advdemos/branches/advdemos/block/initblk.c
0,0 → 1,113
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
/*
* CVS : $Id: initblk.c,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
*
* File: $File$
* Revision: $Revision: 1.1.1.1 $
* Last update: $Date: 2004-05-24 17:54:51 $
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/rr.h"
#include "modules/cbs.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
#include "modules/pi.h"
#include "modules/pc.h"
#include "modules/srp.h"
#include "modules/npp.h"
#include "modules/nop.h"
#include "modules/nopm.h"
 
#include "drivers/keyb.h"
 
/*+ sysyem tick in us +*/
#define TICK 1000
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
extern int __register_sub_init(void);
EDF_register_level(EDF_ENABLE_ALL);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
CBS_register_level(CBS_ENABLE_ALL, 0);
dummy_register_level();
 
SEM_register_module();
 
CABS_register_module();
 
PI_register_module();
PC_register_module();
NPP_register_module();
SRP_register_module();
NOP_register_module();
NOPM_register_module();
 
__register_sub_init();
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
KEYB_PARMS keyb = BASE_KEYB;
extern int __bdev_sub_init(void);
extern void ctrlc_exit(KEY_EVT *k);
HARTPORT_init();
keyb_def_ctrlC(keyb, ctrlc_exit);
KEYB_init(&keyb);
 
__bdev_sub_init();
__call_main__(mb);
 
return (void *)0;
}
/advdemos/branches/advdemos/block/readme
0,0 → 1,33
Hi,
 
These are the block devices demos.
 
- THEY DO NOT WRITE ON YOUR HD, so they are not dangerous.
 
- They do not require a FAT16 Filesystem.
 
 
idetest0:
The demo identifies your Hard Disk characteristics and prints it on
the screen.
 
idetest1:
The demo identifies all the partitions of your HD.
 
idetest2:
The demo allows you to select a sector on the HD and to read it.
 
idetest3:
The demo reads a random sector and then it writes it in the same position.
 
idelin:
The demo reads 16Mb of data from the HD. The data is read block by
block, linearly.
 
idernd:
The demo reads 512Kb of data from the HD. The data is read block by
block, randomly.
 
Enjoy,
 
PJ
/advdemos/branches/advdemos/block/common.h
0,0 → 1,11
 
#ifndef __COMMON_H
#define __COMMON_H
 
void showmessage(char *s);
void waitend(void);
 
void debug_dump_buffer(char *buf, int size);
 
#endif
/advdemos/branches/advdemos/mpeg2/ieee1180
0,0 → 1,245
IEEE 1180 report for mpeg2decode fast integer IDCT:
 
From stefan@lis.e-technik.tu-muenchen.de Thu May 26 08:18:36 1994
 
IEEE test conditions: -L = -256, +H = 255, sign = 1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0058 0.0118 0.0097 0.0057 0.0055 0.0117 0.0120 0.0063
0.0106 0.0157 0.0142 0.0099 0.0115 0.0168 0.0154 0.0123
0.0128 0.0156 0.0152 0.0095 0.0115 0.0147 0.0173 0.0096
0.0055 0.0115 0.0103 0.0078 0.0069 0.0092 0.0113 0.0071
0.0057 0.0134 0.0123 0.0067 0.0050 0.0109 0.0128 0.0065
0.0101 0.0172 0.0159 0.0093 0.0097 0.0148 0.0163 0.0130
0.0113 0.0171 0.0148 0.0103 0.0110 0.0153 0.0149 0.0093
0.0064 0.0123 0.0104 0.0065 0.0064 0.0111 0.0099 0.0066
Worst pmse = 0.017300 (meets spec limit 0.06)
Overall mse = 0.010998 (meets spec limit 0.02)
 
Mean errors:
0.0014 0.0004 0.0003 0.0017 0.0003 0.0011 0.0010 -0.0001
0.0000 0.0003 0.0010 0.0003 0.0007 -0.0006 0.0004 0.0033
0.0000 -0.0008 -0.0006 0.0009 -0.0015 -0.0013 -0.0017 -0.0008
-0.0017 0.0019 -0.0005 0.0010 0.0005 0.0000 -0.0017 -0.0001
0.0007 0.0034 0.0015 0.0021 0.0016 0.0007 -0.0006 0.0011
-0.0007 0.0004 -0.0001 0.0003 0.0003 0.0004 0.0031 -0.0010
0.0009 -0.0005 -0.0004 0.0003 0.0008 -0.0015 -0.0007 -0.0007
0.0024 0.0001 0.0018 -0.0003 -0.0006 -0.0001 0.0009 0.0018
Worst mean error = 0.003400 (meets spec limit 0.015)
Overall mean error = 0.000352 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.8u 0.1s 0:27 95% 0+216k 0+2io 0pf+0w
IEEE test conditions: -L = -5, +H = 5, sign = 1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0008 0.0008 0.0006 0.0006 0.0006 0.0006 0.0007 0.0005
0.0005 0.0003 0.0005 0.0001 0.0003 0.0007 0.0007 0.0004
0.0004 0.0012 0.0011 0.0007 0.0010 0.0008 0.0010 0.0003
0.0004 0.0004 0.0001 0.0002 0.0004 0.0007 0.0009 0.0004
0.0005 0.0005 0.0004 0.0002 0.0006 0.0004 0.0012 0.0003
0.0008 0.0006 0.0007 0.0007 0.0003 0.0012 0.0011 0.0004
0.0006 0.0002 0.0001 0.0002 0.0005 0.0005 0.0007 0.0005
0.0008 0.0004 0.0006 0.0003 0.0008 0.0006 0.0002 0.0003
Worst pmse = 0.001200 (meets spec limit 0.06)
Overall mse = 0.000561 (meets spec limit 0.02)
 
Mean errors:
0.0008 0.0006 0.0000 0.0006 0.0006 0.0002 0.0005 0.0003
0.0005 0.0003 0.0003 0.0001 0.0001 0.0001 0.0005 0.0002
0.0004 0.0006 0.0005 0.0007 0.0006 0.0004 0.0002 -0.0001
0.0002 0.0002 0.0001 0.0002 0.0004 0.0005 0.0003 0.0002
0.0003 0.0003 0.0004 0.0002 0.0006 0.0000 0.0002 0.0003
-0.0002 0.0004 0.0007 0.0005 0.0001 0.0010 0.0005 -0.0002
0.0004 0.0000 0.0001 0.0000 0.0001 0.0003 0.0005 0.0003
0.0006 0.0000 0.0002 0.0003 0.0004 0.0002 0.0002 0.0001
Worst mean error = 0.001000 (meets spec limit 0.015)
Overall mean error = 0.000311 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.7u 0.1s 0:27 95% 0+216k 0+3io 0pf+0w
IEEE test conditions: -L = -300, +H = 300, sign = 1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0068 0.0097 0.0119 0.0064 0.0065 0.0105 0.0112 0.0050
0.0088 0.0130 0.0128 0.0088 0.0111 0.0152 0.0139 0.0109
0.0114 0.0127 0.0157 0.0099 0.0114 0.0137 0.0153 0.0109
0.0052 0.0097 0.0120 0.0060 0.0067 0.0114 0.0099 0.0065
0.0062 0.0096 0.0091 0.0064 0.0076 0.0092 0.0111 0.0058
0.0096 0.0139 0.0166 0.0112 0.0092 0.0141 0.0122 0.0103
0.0121 0.0138 0.0131 0.0089 0.0108 0.0172 0.0127 0.0104
0.0070 0.0109 0.0092 0.0055 0.0057 0.0128 0.0102 0.0069
Worst pmse = 0.017200 (meets spec limit 0.06)
Overall mse = 0.010316 (meets spec limit 0.02)
 
Mean errors:
-0.0010 0.0015 0.0001 -0.0004 0.0005 -0.0001 0.0008 0.0000
0.0004 0.0016 0.0006 0.0000 -0.0001 0.0004 0.0011 0.0001
-0.0008 0.0013 0.0015 0.0003 0.0010 0.0005 -0.0005 0.0021
0.0006 0.0013 -0.0004 0.0000 0.0007 -0.0002 -0.0009 0.0003
0.0004 0.0004 -0.0001 -0.0004 0.0014 0.0018 0.0017 -0.0002
0.0024 0.0007 -0.0002 -0.0018 0.0004 0.0001 0.0010 0.0009
0.0001 -0.0002 0.0005 0.0003 -0.0016 0.0004 0.0013 -0.0006
-0.0012 -0.0017 -0.0008 0.0003 0.0001 0.0018 0.0008 -0.0005
Worst mean error = 0.002400 (meets spec limit 0.015)
Overall mean error = 0.000309 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.8u 0.0s 0:27 95% 0+216k 0+4io 0pf+0w
IEEE test conditions: -L = -256, +H = 255, sign = -1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0061 0.0118 0.0097 0.0057 0.0058 0.0113 0.0115 0.0061
0.0105 0.0159 0.0138 0.0097 0.0113 0.0166 0.0149 0.0123
0.0129 0.0155 0.0152 0.0095 0.0112 0.0145 0.0173 0.0094
0.0059 0.0112 0.0105 0.0076 0.0071 0.0091 0.0113 0.0073
0.0061 0.0130 0.0128 0.0066 0.0051 0.0108 0.0126 0.0067
0.0099 0.0168 0.0161 0.0095 0.0100 0.0149 0.0166 0.0132
0.0113 0.0171 0.0150 0.0101 0.0110 0.0157 0.0152 0.0094
0.0062 0.0121 0.0102 0.0065 0.0061 0.0112 0.0099 0.0065
Worst pmse = 0.017300 (meets spec limit 0.06)
Overall mse = 0.010980 (meets spec limit 0.02)
 
Mean errors:
-0.0005 0.0006 0.0001 -0.0007 0.0006 -0.0003 -0.0003 0.0011
0.0011 0.0003 -0.0002 0.0005 -0.0001 0.0008 0.0001 -0.0027
0.0013 0.0015 0.0010 -0.0001 0.0020 0.0019 0.0025 0.0016
0.0023 -0.0008 0.0011 -0.0002 0.0007 0.0003 0.0019 0.0009
-0.0003 -0.0030 -0.0002 -0.0012 -0.0009 0.0000 0.0010 -0.0005
0.0009 0.0002 0.0015 0.0007 0.0002 0.0001 -0.0026 0.0018
0.0001 0.0011 0.0010 0.0005 -0.0004 0.0023 0.0014 0.0014
-0.0014 0.0007 -0.0014 0.0009 0.0013 0.0006 -0.0007 -0.0007
Worst mean error = 0.003000 (meets spec limit 0.015)
Overall mean error = 0.000355 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.8u 0.1s 0:27 95% 0+216k 0+3io 0pf+0w
IEEE test conditions: -L = -5, +H = 5, sign = -1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0010 0.0007 0.0008 0.0004 0.0008 0.0004 0.0005 0.0007
0.0005 0.0007 0.0005 0.0004 0.0006 0.0005 0.0005 0.0003
0.0003 0.0011 0.0009 0.0007 0.0008 0.0006 0.0011 0.0006
0.0003 0.0004 0.0002 0.0002 0.0003 0.0006 0.0008 0.0006
0.0004 0.0005 0.0006 0.0006 0.0003 0.0007 0.0007 0.0003
0.0013 0.0006 0.0008 0.0005 0.0004 0.0006 0.0008 0.0004
0.0003 0.0003 0.0003 0.0002 0.0005 0.0004 0.0006 0.0005
0.0005 0.0003 0.0006 0.0005 0.0011 0.0007 0.0005 0.0003
Worst pmse = 0.001300 (meets spec limit 0.06)
Overall mse = 0.000561 (meets spec limit 0.02)
 
Mean errors:
0.0002 0.0005 0.0008 0.0000 0.0002 0.0004 0.0003 0.0007
0.0001 0.0003 0.0003 0.0002 0.0006 0.0003 0.0001 0.0003
-0.0001 0.0007 0.0003 0.0001 0.0002 0.0006 0.0005 0.0006
0.0001 0.0004 0.0002 0.0002 0.0001 0.0002 0.0004 0.0004
0.0002 0.0005 0.0006 0.0004 0.0001 0.0005 0.0005 0.0003
0.0009 0.0002 0.0000 0.0001 0.0004 0.0000 0.0006 0.0004
0.0003 0.0003 0.0003 0.0002 0.0003 0.0000 0.0004 0.0003
0.0003 0.0003 0.0004 0.0003 0.0007 0.0005 0.0005 0.0003
Worst mean error = 0.000900 (meets spec limit 0.015)
Overall mean error = 0.000333 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.7u 0.1s 0:27 95% 0+216k 0+0io 0pf+0w
IEEE test conditions: -L = -300, +H = 300, sign = -1, #iters = 10000
Peak absolute values of errors:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Worst peak error = 1 (meets spec limit 1)
 
Mean square errors:
0.0067 0.0097 0.0118 0.0060 0.0066 0.0107 0.0113 0.0049
0.0082 0.0132 0.0128 0.0088 0.0110 0.0152 0.0140 0.0109
0.0122 0.0125 0.0156 0.0098 0.0113 0.0139 0.0152 0.0106
0.0054 0.0097 0.0121 0.0064 0.0067 0.0110 0.0096 0.0062
0.0064 0.0099 0.0090 0.0067 0.0078 0.0089 0.0112 0.0057
0.0098 0.0136 0.0165 0.0111 0.0090 0.0138 0.0120 0.0103
0.0121 0.0135 0.0131 0.0087 0.0107 0.0168 0.0128 0.0102
0.0069 0.0109 0.0091 0.0057 0.0061 0.0125 0.0103 0.0070
Worst pmse = 0.016800 (meets spec limit 0.06)
Overall mse = 0.010283 (meets spec limit 0.02)
 
Mean errors:
0.0015 -0.0009 0.0006 0.0012 0.0002 0.0007 -0.0001 0.0005
0.0004 -0.0010 0.0000 0.0004 0.0006 0.0004 -0.0004 0.0007
0.0018 -0.0009 -0.0006 0.0000 -0.0003 -0.0001 0.0014 -0.0006
-0.0002 -0.0011 0.0009 0.0004 -0.0003 0.0010 0.0010 0.0000
0.0004 0.0001 0.0010 0.0011 -0.0008 -0.0017 -0.0006 0.0009
-0.0020 0.0000 0.0007 0.0021 0.0002 0.0002 -0.0004 -0.0003
0.0003 0.0005 -0.0003 -0.0001 0.0017 0.0002 -0.0004 0.0010
0.0015 0.0023 0.0013 0.0003 0.0005 -0.0011 -0.0003 0.0006
Worst mean error = 0.002300 (meets spec limit 0.015)
Overall mean error = 0.000252 (meets spec limit 0.0015)
 
0 elements of IDCT(0) were not zero
 
 
25.8u 0.0s 0:27 94% 0+216k 0+3io 0pf+0w
 
/advdemos/branches/advdemos/mpeg2/makefile.lib
0,0 → 1,54
#
# The mpeg library
#
 
# (see sources for copyrights)
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
LIBRARY = mpeg2
 
OBJS_PATH = $(BASE)/ports/mpeg2
 
DECODER_SRC = util.c \
video.c \
parseblock.c \
motionvector.c \
decoders.c \
jrevdct.c \
wrapper.c \
gdith.c \
gdithmni.c \
readfile.c \
16bit.c
 
DITHER_SRC = fs2.c \
fs2fast.c \
fs4.c \
hybrid.c \
hybriderr.c \
2x2.c \
gray.c \
mono.c \
ordered.c \
ordered2.c \
mb_ordered.c
 
SRCS= $(DECODER_SRC) $(DITHER_SRC)
 
OBJS= mpeg2dec.o getpic.o motion.o getvlc.o \
gethdr.o getblk.o getbits.o store.o \
recon.o spatscal.o idct.o idctref.o \
display.o systems.o subspic.o verify.o
 
#C_WARN += -Wno-unused -Wno-uninitialized -Wno-implicit-function-declaration \
# -Wno-switch -Wno-return-type
 
#C_DEF += -DNOCONTROLS
#C_INC += -I.
 
include $(BASE)/config/lib.mk
 
/advdemos/branches/advdemos/mpeg2/jetctrl.c
0,0 → 1,163
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: jetctrl.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
/*
* this file is directly derived from the demos/jumpball/jetctrl.c .
* I just added this controls to check when the system will become overloaded
*/
 
#define WCET_JETDUMMY 200
#define PERIOD_JETDUMMY 100000
#define DUMMY_PID 1
 
#define JET_DUMMY_WIDTH (CMD_WIDTH-370)
#define JET_DUMMY_HEIGHT (CMD_HEIGHT-40)
 
/* the point (x, y) is the top left corner */
#define JET_DUMMY_X (TRACK_X1+360)
#define JET_DUMMY_Y (TRACK_Y2+32)
 
// from jetdummy in the auto demo
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
/* Track dimensions */
#define TRACK_WIDTH 500
#define TRACK_HEIGHT 500
/* Track position */
#define TRACK_X1 0
#define TRACK_Y1 0
#define TRACK_X2 TRACK_X1+TRACK_WIDTH-1
#define TRACK_Y2 TRACK_Y1+TRACK_HEIGHT-1
#define CMD_WIDTH TRACK_WIDTH
#define CMD_HEIGHT (SCREEN_HEIGHT-TRACK_HEIGHT-3)
 
// JetControl
 
#include "kernel/func.h"
#include "drivers/glib.h"
 
/* useful colors... */
int white;
int black;
int red;
int lightgray;
 
TASK jetdummy_task(void *arg)
{
TIME now_dummy, last_dummy, diff_dummy, slice;
struct timespec now, last, diff;
int x = 0;
int height;
 
NULL_TIMESPEC(&last);
last_dummy = 0;
for (;;) {
task_nopreempt();
jet_getstat(DUMMY_PID, NULL, NULL, NULL, &now_dummy);
sys_gettime(&now);
task_preempt();
 
SUBTIMESPEC(&now, &last, &diff);
slice = diff.tv_sec * 1000000 + diff.tv_nsec/1000;
diff_dummy = now_dummy - last_dummy;
 
height = (int)(JET_DUMMY_HEIGHT*((float)diff_dummy)/((float)slice));
 
TIMESPEC_ASSIGN(&last, &now);
last_dummy = now_dummy;
 
grx_line(JET_DUMMY_X+x,JET_DUMMY_Y,
JET_DUMMY_X+x,JET_DUMMY_Y+height ,black);
grx_line(JET_DUMMY_X+x,JET_DUMMY_Y+height,
JET_DUMMY_X+x,JET_DUMMY_Y+JET_DUMMY_HEIGHT,white);
grx_line(JET_DUMMY_X+(x+1)%JET_DUMMY_WIDTH,JET_DUMMY_Y,
JET_DUMMY_X+(x+1)%JET_DUMMY_WIDTH,JET_DUMMY_Y+JET_DUMMY_HEIGHT,255);
 
x = (x+1)%JET_DUMMY_WIDTH;
 
task_endcycle();
}
}
 
void init_jetcontrol(void)
{
SOFT_TASK_MODEL m4;
 
PID p4;
 
/* useful colors ... */
white = rgb16(255,255,255);
black = rgb16(0,0,0);
red = rgb16(255,0,0);
lightgray = rgb16(128,128,128);
 
/* scenario */
grx_text("System load",
JET_DUMMY_X+8, JET_DUMMY_Y-10, lightgray, black);
grx_rect(JET_DUMMY_X-1, JET_DUMMY_Y-1,
JET_DUMMY_X+JET_DUMMY_WIDTH, JET_DUMMY_Y+JET_DUMMY_HEIGHT+1, lightgray);
 
grx_text("100%", JET_DUMMY_X-40, JET_DUMMY_Y, lightgray, black);
grx_text(" 0%", JET_DUMMY_X-40, JET_DUMMY_Y+JET_DUMMY_HEIGHT-8, lightgray, black);
 
grx_line(JET_DUMMY_X-1, JET_DUMMY_Y, JET_DUMMY_X-5, JET_DUMMY_Y, lightgray);
grx_line(JET_DUMMY_X-1, JET_DUMMY_Y+JET_DUMMY_HEIGHT, JET_DUMMY_X-5, JET_DUMMY_Y+JET_DUMMY_HEIGHT, lightgray);
 
/* jetdummy task */
soft_task_default_model(m4);
soft_task_def_period(m4, PERIOD_JETDUMMY);
soft_task_def_met(m4, WCET_JETDUMMY);
soft_task_def_usemath(m4);
p4 = task_create("jdmy", jetdummy_task, &m4, NULL);
if (p4 == -1) {
grx_close();
perror("Could not create task <jetdummy>");
sys_end();
}
task_activate(p4);
}
 
/advdemos/branches/advdemos/mpeg2/config.h
0,0 → 1,45
/* config.h, configuration defines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* define NON_ANSI_COMPILER for compilers without function prototyping */
/* #define NON_ANSI_COMPILER */
 
#ifdef NON_ANSI_COMPILER
#define _ANSI_ARGS_(x) ()
#else
#define _ANSI_ARGS_(x) x
#endif
 
#define RB "rb"
#define WB "wb"
 
#ifndef O_BINARY
#define O_BINARY 0
 
#endif
/advdemos/branches/advdemos/mpeg2/getpic.c
0,0 → 1,1225
/* getpic.c, picture decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes*/
static void picture_data _ANSI_ARGS_((int framenum));
static void macroblock_modes _ANSI_ARGS_((int *pmacroblock_type, int *pstwtype,
int *pstwclass, int *pmotion_type, int *pmotion_vector_count, int *pmv_format, int *pdmv,
int *pmvscale, int *pdct_type));
static void Clear_Block _ANSI_ARGS_((int comp));
static void Sum_Block _ANSI_ARGS_((int comp));
static void Saturate _ANSI_ARGS_((short *bp));
static void Add_Block _ANSI_ARGS_((int comp, int bx, int by,
int dct_type, int addflag));
static void Update_Picture_Buffers _ANSI_ARGS_((void));
static void frame_reorder _ANSI_ARGS_((int bitstream_framenum,
int sequence_framenum));
static void Decode_SNR_Macroblock _ANSI_ARGS_((int *SNRMBA, int *SNRMBAinc,
int MBA, int MBAmax, int *dct_type));
 
static void motion_compensation _ANSI_ARGS_((int MBA, int macroblock_type,
int motion_type, int PMV[2][2][2], int motion_vertical_field_select[2][2],
int dmvector[2], int stwtype, int dct_type));
 
static void skipped_macroblock _ANSI_ARGS_((int dc_dct_pred[3],
int PMV[2][2][2], int *motion_type, int motion_vertical_field_select[2][2],
int *stwtype, int *macroblock_type));
 
static int slice _ANSI_ARGS_((int framenum, int MBAmax));
 
static int start_of_slice _ANSI_ARGS_ ((int MBAmax, int *MBA,
int *MBAinc, int dc_dct_pred[3], int PMV[2][2][2]));
 
static int decode_macroblock _ANSI_ARGS_((int *macroblock_type,
int *stwtype, int *stwclass, int *motion_type, int *dct_type,
int PMV[2][2][2], int dc_dct_pred[3],
int motion_vertical_field_select[2][2], int dmvector[2]));
 
 
/* decode one frame or field picture */
void Decode_Picture(bitstream_framenum, sequence_framenum)
int bitstream_framenum, sequence_framenum;
{
 
if (picture_structure==FRAME_PICTURE && Second_Field)
{
/* recover from illegal number of field pictures */
printf("odd number of field pictures\n");
Second_Field = 0;
}
 
/* IMPLEMENTATION: update picture buffer pointers */
Update_Picture_Buffers();
 
#ifdef VERIFY
Check_Headers(bitstream_framenum, sequence_framenum);
#endif /* VERIFY */
 
/* ISO/IEC 13818-4 section 2.4.5.4 "frame buffer intercept method" */
/* (section number based on November 1995 (Dallas) draft of the
conformance document) */
if(Ersatz_Flag)
Substitute_Frame_Buffer(bitstream_framenum, sequence_framenum);
 
/* form spatial scalable picture */
/* form spatial scalable picture */
/* ISO/IEC 13818-2 section 7.7: Spatial scalability */
if (base.pict_scal && !Second_Field)
{
Spatial_Prediction();
}
 
/* decode picture data ISO/IEC 13818-2 section 6.2.3.7 */
picture_data(bitstream_framenum);
 
/* write or display current or previously decoded reference frame */
/* ISO/IEC 13818-2 section 6.1.1.11: Frame reordering */
frame_reorder(bitstream_framenum, sequence_framenum);
 
if (picture_structure!=FRAME_PICTURE)
Second_Field = !Second_Field;
}
 
 
/* decode all macroblocks of the current picture */
/* stages described in ISO/IEC 13818-2 section 7 */
static void picture_data(framenum)
int framenum;
{
int MBAmax;
int ret;
 
/* number of macroblocks per picture */
MBAmax = mb_width*mb_height;
 
if (picture_structure!=FRAME_PICTURE)
MBAmax>>=1; /* field picture has half as mnay macroblocks as frame */
 
for(;;)
{
if((ret=slice(framenum, MBAmax))<0)
return;
}
 
}
 
 
 
/* decode all macroblocks of the current picture */
/* ISO/IEC 13818-2 section 6.3.16 */
static int slice(framenum, MBAmax)
int framenum, MBAmax;
{
int MBA;
int MBAinc, macroblock_type, motion_type, dct_type;
int dc_dct_pred[3];
int PMV[2][2][2], motion_vertical_field_select[2][2];
int dmvector[2];
int stwtype, stwclass;
int SNRMBA, SNRMBAinc;
int ret;
 
MBA = 0; /* macroblock address */
MBAinc = 0;
 
if((ret=start_of_slice(MBAmax, &MBA, &MBAinc, dc_dct_pred, PMV))!=1)
return(ret);
 
if (Two_Streams && enhan.scalable_mode==SC_SNR)
{
SNRMBA=0;
SNRMBAinc=0;
}
 
Fault_Flag=0;
 
for (;;)
{
 
/* this is how we properly exit out of picture */
if (MBA>=MBAmax)
return(-1); /* all macroblocks decoded */
 
#ifdef TRACE
if (Trace_Flag)
printf("frame %d, MB %d\n",framenum,MBA);
#endif /* TRACE */
 
#ifdef DISPLAY
if (!progressive_frame && picture_structure==FRAME_PICTURE
&& MBA==(MBAmax>>1) && framenum!=0 && Output_Type==T_X11
&& !Display_Progressive_Flag)
{
Display_Second_Field();
}
#endif
 
ld = &base;
 
if (MBAinc==0)
{
if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
ld = &enhan;
 
if (!Show_Bits(23) || Fault_Flag) /* next_start_code or fault */
{
resync: /* if Fault_Flag: resynchronize to next next_start_code */
Fault_Flag = 0;
return(0); /* trigger: go to next slice */
}
else /* neither next_start_code nor Fault_Flag */
{
if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
ld = &enhan;
 
/* decode macroblock address increment */
MBAinc = Get_macroblock_address_increment();
 
if (Fault_Flag) goto resync;
}
}
 
if (MBA>=MBAmax)
{
/* MBAinc points beyond picture dimensions */
if (!Quiet_Flag)
printf("Too many macroblocks in picture\n");
return(-1);
}
 
if (MBAinc==1) /* not skipped */
{
ret = decode_macroblock(&macroblock_type, &stwtype, &stwclass,
&motion_type, &dct_type, PMV, dc_dct_pred,
motion_vertical_field_select, dmvector);
 
if(ret==-1)
return(-1);
if(ret==0)
goto resync;
 
}
else /* MBAinc!=1: skipped macroblock */
{
/* ISO/IEC 13818-2 section 7.6.6 */
skipped_macroblock(dc_dct_pred, PMV, &motion_type,
motion_vertical_field_select, &stwtype, &macroblock_type);
}
 
/* SCALABILITY: SNR */
/* ISO/IEC 13818-2 section 7.8 */
/* NOTE: we currently ignore faults encountered in this routine */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
Decode_SNR_Macroblock(&SNRMBA, &SNRMBAinc, MBA, MBAmax, &dct_type);
 
/* ISO/IEC 13818-2 section 7.6 */
motion_compensation(MBA, macroblock_type, motion_type, PMV,
motion_vertical_field_select, dmvector, stwtype, dct_type);
 
 
/* advance to next macroblock */
MBA++;
MBAinc--;
/* SCALABILITY: SNR */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
{
SNRMBA++;
SNRMBAinc--;
}
 
if (MBA>=MBAmax)
return(-1); /* all macroblocks decoded */
}
}
 
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
static void macroblock_modes(pmacroblock_type,pstwtype,pstwclass,
pmotion_type,pmotion_vector_count,pmv_format,pdmv,pmvscale,pdct_type)
int *pmacroblock_type, *pstwtype, *pstwclass;
int *pmotion_type, *pmotion_vector_count, *pmv_format, *pdmv, *pmvscale;
int *pdct_type;
{
int macroblock_type;
int stwtype, stwcode, stwclass;
int motion_type = 0;
int motion_vector_count, mv_format, dmv, mvscale;
int dct_type;
static unsigned char stwc_table[3][4]
= { {6,3,7,4}, {2,1,5,4}, {2,5,7,4} };
static unsigned char stwclass_table[9]
= {0, 1, 2, 1, 1, 2, 3, 3, 4};
 
/* get macroblock_type */
macroblock_type = Get_macroblock_type();
 
if (Fault_Flag) return;
 
/* get spatial_temporal_weight_code */
if (macroblock_type & MB_WEIGHT)
{
if (spatial_temporal_weight_code_table_index==0)
stwtype = 4;
else
{
stwcode = Get_Bits(2);
#ifdef TRACE
if (Trace_Flag)
{
printf("spatial_temporal_weight_code (");
Print_Bits(stwcode,2,2);
printf("): %d\n",stwcode);
}
#endif /* TRACE */
stwtype = stwc_table[spatial_temporal_weight_code_table_index-1][stwcode];
}
}
else
stwtype = (macroblock_type & MB_CLASS4) ? 8 : 0;
 
/* SCALABILITY: derive spatial_temporal_weight_class (Table 7-18) */
stwclass = stwclass_table[stwtype];
 
/* get frame/field motion type */
if (macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD))
{
if (picture_structure==FRAME_PICTURE) /* frame_motion_type */
{
motion_type = frame_pred_frame_dct ? MC_FRAME : Get_Bits(2);
#ifdef TRACE
if (!frame_pred_frame_dct && Trace_Flag)
{
printf("frame_motion_type (");
Print_Bits(motion_type,2,2);
printf("): %s\n",motion_type==MC_FIELD?"Field":
motion_type==MC_FRAME?"Frame":
motion_type==MC_DMV?"Dual_Prime":"Invalid");
}
#endif /* TRACE */
}
else /* field_motion_type */
{
motion_type = Get_Bits(2);
#ifdef TRACE
if (Trace_Flag)
{
printf("field_motion_type (");
Print_Bits(motion_type,2,2);
printf("): %s\n",motion_type==MC_FIELD?"Field":
motion_type==MC_16X8?"16x8 MC":
motion_type==MC_DMV?"Dual_Prime":"Invalid");
}
#endif /* TRACE */
}
}
else if ((macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
{
/* concealment motion vectors */
motion_type = (picture_structure==FRAME_PICTURE) ? MC_FRAME : MC_FIELD;
}
#if 0
else
{
printf("maroblock_modes(): unknown macroblock type\n");
motion_type = -1;
}
#endif
 
/* derive motion_vector_count, mv_format and dmv, (table 6-17, 6-18) */
if (picture_structure==FRAME_PICTURE)
{
motion_vector_count = (motion_type==MC_FIELD && stwclass<2) ? 2 : 1;
mv_format = (motion_type==MC_FRAME) ? MV_FRAME : MV_FIELD;
}
else
{
motion_vector_count = (motion_type==MC_16X8) ? 2 : 1;
mv_format = MV_FIELD;
}
 
dmv = (motion_type==MC_DMV); /* dual prime */
 
/* field mv predictions in frame pictures have to be scaled
* ISO/IEC 13818-2 section 7.6.3.1 Decoding the motion vectors
* IMPLEMENTATION: mvscale is derived for later use in motion_vectors()
* it displaces the stage:
*
* if((mv_format=="field")&&(t==1)&&(picture_structure=="Frame picture"))
* prediction = PMV[r][s][t] DIV 2;
*/
 
mvscale = ((mv_format==MV_FIELD) && (picture_structure==FRAME_PICTURE));
 
/* get dct_type (frame DCT / field DCT) */
dct_type = (picture_structure==FRAME_PICTURE)
&& (!frame_pred_frame_dct)
&& (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA))
? Get_Bits(1)
: 0;
 
#ifdef TRACE
if (Trace_Flag && (picture_structure==FRAME_PICTURE)
&& (!frame_pred_frame_dct)
&& (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA)))
printf("dct_type (%d): %s\n",dct_type,dct_type?"Field":"Frame");
#endif /* TRACE */
 
/* return values */
*pmacroblock_type = macroblock_type;
*pstwtype = stwtype;
*pstwclass = stwclass;
*pmotion_type = motion_type;
*pmotion_vector_count = motion_vector_count;
*pmv_format = mv_format;
*pdmv = dmv;
*pmvscale = mvscale;
*pdct_type = dct_type;
}
 
 
/* move/add 8x8-Block from block[comp] to backward_reference_frame */
/* copy reconstructed 8x8 block from block[comp] to current_frame[]
* ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data
* This stage also embodies some of the operations implied by:
* - ISO/IEC 13818-2 section 7.6.7: Combining predictions
* - ISO/IEC 13818-2 section 6.1.3: Macroblock
*/
static void Add_Block(comp,bx,by,dct_type,addflag)
int comp,bx,by,dct_type,addflag;
{
int cc,i, j, iincr;
unsigned char *rfp;
short *bp;
 
/* derive color component index */
/* equivalent to ISO/IEC 13818-2 Table 7-1 */
cc = (comp<4) ? 0 : (comp&1)+1; /* color component index */
 
if (cc==0)
{
/* luminance */
 
if (picture_structure==FRAME_PICTURE)
if (dct_type)
{
/* field DCT coding */
rfp = current_frame[0]
+ Coded_Picture_Width*(by+((comp&2)>>1)) + bx + ((comp&1)<<3);
iincr = (Coded_Picture_Width<<1) - 8;
}
else
{
/* frame DCT coding */
rfp = current_frame[0]
+ Coded_Picture_Width*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
iincr = Coded_Picture_Width - 8;
}
else
{
/* field picture */
rfp = current_frame[0]
+ (Coded_Picture_Width<<1)*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
iincr = (Coded_Picture_Width<<1) - 8;
}
}
else
{
/* chrominance */
 
/* scale coordinates */
if (chroma_format!=CHROMA444)
bx >>= 1;
if (chroma_format==CHROMA420)
by >>= 1;
if (picture_structure==FRAME_PICTURE)
{
if (dct_type && (chroma_format!=CHROMA420))
{
/* field DCT coding */
rfp = current_frame[cc]
+ Chroma_Width*(by+((comp&2)>>1)) + bx + (comp&8);
iincr = (Chroma_Width<<1) - 8;
}
else
{
/* frame DCT coding */
rfp = current_frame[cc]
+ Chroma_Width*(by+((comp&2)<<2)) + bx + (comp&8);
iincr = Chroma_Width - 8;
}
}
else
{
/* field picture */
rfp = current_frame[cc]
+ (Chroma_Width<<1)*(by+((comp&2)<<2)) + bx + (comp&8);
iincr = (Chroma_Width<<1) - 8;
}
}
 
bp = ld->block[comp];
 
if (addflag)
{
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
{
*rfp = Clip[*bp++ + *rfp];
rfp++;
}
 
rfp+= iincr;
}
}
else
{
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
*rfp++ = Clip[*bp++ + 128];
 
rfp+= iincr;
}
}
}
 
 
/* ISO/IEC 13818-2 section 7.8 */
static void Decode_SNR_Macroblock(SNRMBA, SNRMBAinc, MBA, MBAmax, dct_type)
int *SNRMBA, *SNRMBAinc;
int MBA, MBAmax;
int *dct_type;
{
int SNRmacroblock_type, SNRcoded_block_pattern, SNRdct_type, dummy;
int slice_vert_pos_ext, quantizer_scale_code, comp, code;
 
ld = &enhan;
 
if (*SNRMBAinc==0)
{
if (!Show_Bits(23)) /* next_start_code */
{
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
printf("SNR: Premature end of picture\n");
return;
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
/* decode macroblock address increment */
*SNRMBAinc = Get_macroblock_address_increment();
 
/* set current location */
*SNRMBA =
((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *SNRMBAinc - 1;
 
*SNRMBAinc = 1; /* first macroblock in slice: not skipped */
}
else /* not next_start_code */
{
if (*SNRMBA>=MBAmax)
{
if (!Quiet_Flag)
printf("Too many macroblocks in picture\n");
return;
}
 
/* decode macroblock address increment */
*SNRMBAinc = Get_macroblock_address_increment();
}
}
 
if (*SNRMBA!=MBA)
{
/* streams out of sync */
if (!Quiet_Flag)
printf("Cant't synchronize streams\n");
return;
}
 
if (*SNRMBAinc==1) /* not skipped */
{
macroblock_modes(&SNRmacroblock_type, &dummy, &dummy,
&dummy, &dummy, &dummy, &dummy, &dummy,
&SNRdct_type);
 
if (SNRmacroblock_type & MACROBLOCK_PATTERN)
*dct_type = SNRdct_type;
 
if (SNRmacroblock_type & MACROBLOCK_QUANT)
{
quantizer_scale_code = Get_Bits(5);
ld->quantizer_scale =
ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] : quantizer_scale_code<<1;
}
 
/* macroblock_pattern */
if (SNRmacroblock_type & MACROBLOCK_PATTERN)
{
SNRcoded_block_pattern = Get_coded_block_pattern();
 
if (chroma_format==CHROMA422)
SNRcoded_block_pattern = (SNRcoded_block_pattern<<2) | Get_Bits(2); /* coded_block_pattern_1 */
else if (chroma_format==CHROMA444)
SNRcoded_block_pattern = (SNRcoded_block_pattern<<6) | Get_Bits(6); /* coded_block_pattern_2 */
}
else
SNRcoded_block_pattern = 0;
 
/* decode blocks */
for (comp=0; comp<block_count; comp++)
{
Clear_Block(comp);
 
if (SNRcoded_block_pattern & (1<<(block_count-1-comp)))
Decode_MPEG2_Non_Intra_Block(comp);
}
}
else /* SNRMBAinc!=1: skipped macroblock */
{
for (comp=0; comp<block_count; comp++)
Clear_Block(comp);
}
 
ld = &base;
}
 
 
 
/* IMPLEMENTATION: set scratch pad macroblock to zero */
static void Clear_Block(comp)
int comp;
{
short *Block_Ptr;
int i;
 
Block_Ptr = ld->block[comp];
 
for (i=0; i<64; i++)
*Block_Ptr++ = 0;
}
 
 
/* SCALABILITY: add SNR enhancement layer block data to base layer */
/* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from the two layes */
static void Sum_Block(comp)
int comp;
{
short *Block_Ptr1, *Block_Ptr2;
int i;
 
Block_Ptr1 = base.block[comp];
Block_Ptr2 = enhan.block[comp];
 
for (i=0; i<64; i++)
*Block_Ptr1++ += *Block_Ptr2++;
}
 
 
/* limit coefficients to -2048..2047 */
/* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
static void Saturate(Block_Ptr)
short *Block_Ptr;
{
int i, sum, val;
 
sum = 0;
 
/* ISO/IEC 13818-2 section 7.4.3: Saturation */
for (i=0; i<64; i++)
{
val = Block_Ptr[i];
 
if (val>2047)
val = 2047;
else if (val<-2048)
val = -2048;
 
Block_Ptr[i] = val;
sum+= val;
}
 
/* ISO/IEC 13818-2 section 7.4.4: Mismatch control */
if ((sum&1)==0)
Block_Ptr[63]^= 1;
 
}
 
 
/* reuse old picture buffers as soon as they are no longer needed
based on life-time axioms of MPEG */
static void Update_Picture_Buffers()
{
int cc; /* color component index */
unsigned char *tmp; /* temporary swap pointer */
 
for (cc=0; cc<3; cc++)
{
/* B pictures do not need to be save for future reference */
if (picture_coding_type==B_TYPE)
{
current_frame[cc] = auxframe[cc];
}
else
{
/* only update at the beginning of the coded frame */
if (!Second_Field)
{
tmp = forward_reference_frame[cc];
 
/* the previously decoded reference frame is stored
coincident with the location where the backward
reference frame is stored (backwards prediction is not
needed in P pictures) */
forward_reference_frame[cc] = backward_reference_frame[cc];
/* update pointer for potential future B pictures */
backward_reference_frame[cc] = tmp;
}
 
/* can erase over old backward reference frame since it is not used
in a P picture, and since any subsequent B pictures will use the
previously decoded I or P frame as the backward_reference_frame */
current_frame[cc] = backward_reference_frame[cc];
}
 
/* IMPLEMENTATION:
one-time folding of a line offset into the pointer which stores the
memory address of the current frame saves offsets and conditional
branches throughout the remainder of the picture processing loop */
if (picture_structure==BOTTOM_FIELD)
current_frame[cc]+= (cc==0) ? Coded_Picture_Width : Chroma_Width;
}
}
 
 
/* store last frame */
 
void Output_Last_Frame_of_Sequence(Framenum)
int Framenum;
{
if (Second_Field)
printf("last frame incomplete, not stored\n");
else
Write_Frame(backward_reference_frame,Framenum-1);
}
 
 
 
static void frame_reorder(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum, Sequence_Framenum;
{
/* tracking variables to insure proper output in spatial scalability */
static int Oldref_progressive_frame, Newref_progressive_frame;
 
if (Sequence_Framenum!=0)
{
if (picture_structure==FRAME_PICTURE || Second_Field)
{
if (picture_coding_type==B_TYPE)
Write_Frame(auxframe,Bitstream_Framenum-1);
else
{
Newref_progressive_frame = progressive_frame;
progressive_frame = Oldref_progressive_frame;
 
Write_Frame(forward_reference_frame,Bitstream_Framenum-1);
 
Oldref_progressive_frame = progressive_frame = Newref_progressive_frame;
}
}
#ifdef DISPLAY
else if (Output_Type==T_X11)
{
if(!Display_Progressive_Flag)
Display_Second_Field();
}
#endif
}
else
Oldref_progressive_frame = progressive_frame;
 
}
 
 
/* ISO/IEC 13818-2 section 7.6 */
static void motion_compensation(MBA, macroblock_type, motion_type, PMV,
motion_vertical_field_select, dmvector, stwtype, dct_type)
int MBA;
int macroblock_type;
int motion_type;
int PMV[2][2][2];
int motion_vertical_field_select[2][2];
int dmvector[2];
int stwtype;
int dct_type;
{
int bx, by;
int comp;
 
/* derive current macroblock position within picture */
/* ISO/IEC 13818-2 section 6.3.1.6 and 6.3.1.7 */
bx = 16*(MBA%mb_width);
by = 16*(MBA/mb_width);
 
/* motion compensation */
if (!(macroblock_type & MACROBLOCK_INTRA))
form_predictions(bx,by,macroblock_type,motion_type,PMV,
motion_vertical_field_select,dmvector,stwtype);
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
/* copy or add block data into picture */
for (comp=0; comp<block_count; comp++)
{
/* SCALABILITY: SNR */
/* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from
the two a layers */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
Sum_Block(comp); /* add SNR enhancement layer data to base layer */
 
/* MPEG-2 saturation and mismatch control */
/* base layer could be MPEG-1 stream, enhancement MPEG-2 SNR */
/* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
if ((Two_Streams && enhan.scalable_mode==SC_SNR) || ld->MPEG2_Flag)
Saturate(ld->block[comp]);
 
/* ISO/IEC 13818-2 section Annex A: inverse DCT */
if (Reference_IDCT_Flag)
Reference_IDCT(ld->block[comp]);
else
Fast_IDCT(ld->block[comp]);
/* ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data */
Add_Block(comp,bx,by,dct_type,(macroblock_type & MACROBLOCK_INTRA)==0);
}
 
}
 
 
 
/* ISO/IEC 13818-2 section 7.6.6 */
static void skipped_macroblock(dc_dct_pred, PMV, motion_type,
motion_vertical_field_select, stwtype, macroblock_type)
int dc_dct_pred[3];
int PMV[2][2][2];
int *motion_type;
int motion_vertical_field_select[2][2];
int *stwtype;
int *macroblock_type;
{
int comp;
/* SCALABILITY: Data Paritioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
for (comp=0; comp<block_count; comp++)
Clear_Block(comp);
 
/* reset intra_dc predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
 
/* reset motion vector predictors */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
if (picture_coding_type==P_TYPE)
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
 
/* derive motion_type */
if (picture_structure==FRAME_PICTURE)
*motion_type = MC_FRAME;
else
{
*motion_type = MC_FIELD;
 
/* predict from field of same parity */
/* ISO/IEC 13818-2 section 7.6.6.1 and 7.6.6.3: P field picture and B field
picture */
motion_vertical_field_select[0][0]=motion_vertical_field_select[0][1] =
(picture_structure==BOTTOM_FIELD);
}
 
/* skipped I are spatial-only predicted, */
/* skipped P and B are temporal-only predicted */
/* ISO/IEC 13818-2 section 7.7.6: Skipped macroblocks */
*stwtype = (picture_coding_type==I_TYPE) ? 8 : 0;
 
/* IMPLEMENTATION: clear MACROBLOCK_INTRA */
*macroblock_type&= ~MACROBLOCK_INTRA;
 
}
 
 
/* return==-1 means go to next picture */
/* the expression "start of slice" is used throughout the normative
body of the MPEG specification */
static int start_of_slice(MBAmax, MBA, MBAinc,
dc_dct_pred, PMV)
int MBAmax;
int *MBA;
int *MBAinc;
int dc_dct_pred[3];
int PMV[2][2][2];
{
unsigned int code;
int slice_vert_pos_ext;
 
ld = &base;
 
Fault_Flag = 0;
 
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
printf("start_of_slice(): Premature end of picture\n");
 
return(-1); /* trigger: go to next picture */
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
{
ld = &enhan;
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
printf("DP: Premature end of picture\n");
return(-1); /* trigger: go to next picture */
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
if (base.priority_breakpoint!=1)
ld = &base;
}
 
/* decode macroblock address increment */
*MBAinc = Get_macroblock_address_increment();
 
if (Fault_Flag)
{
printf("start_of_slice(): MBAinc unsuccessful\n");
return(0); /* trigger: go to next slice */
}
 
/* set current location */
/* NOTE: the arithmetic used to derive macroblock_address below is
* equivalent to ISO/IEC 13818-2 section 6.3.17: Macroblock
*/
*MBA = ((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *MBAinc - 1;
*MBAinc = 1; /* first macroblock in slice: not skipped */
 
/* reset all DC coefficient and motion vector predictors */
/* reset all DC coefficient and motion vector predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
 
/* successfull: trigger decode macroblocks in slice */
return(1);
}
 
 
/* ISO/IEC 13818-2 sections 7.2 through 7.5 */
static int decode_macroblock(macroblock_type, stwtype, stwclass,
motion_type, dct_type, PMV, dc_dct_pred,
motion_vertical_field_select, dmvector)
int *macroblock_type;
int *stwtype;
int *stwclass;
int *motion_type;
int *dct_type;
int PMV[2][2][2];
int dc_dct_pred[3];
int motion_vertical_field_select[2][2];
int dmvector[2];
{
/* locals */
int quantizer_scale_code;
int comp;
 
int motion_vector_count;
int mv_format;
int dmv;
int mvscale;
int coded_block_pattern;
 
/* SCALABILITY: Data Patitioning */
if (base.scalable_mode==SC_DP)
{
if (base.priority_breakpoint<=2)
ld = &enhan;
else
ld = &base;
}
 
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
macroblock_modes(macroblock_type, stwtype, stwclass,
motion_type, &motion_vector_count, &mv_format, &dmv, &mvscale,
dct_type);
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
if (*macroblock_type & MACROBLOCK_QUANT)
{
quantizer_scale_code = Get_Bits(5);
 
#ifdef TRACE
if (Trace_Flag)
{
printf("quantiser_scale_code (");
Print_Bits(quantizer_scale_code,5,5);
printf("): %d\n",quantizer_scale_code);
}
#endif /* TRACE */
 
/* ISO/IEC 13818-2 section 7.4.2.2: Quantizer scale factor */
if (ld->MPEG2_Flag)
ld->quantizer_scale =
ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code]
: (quantizer_scale_code << 1);
else
ld->quantizer_scale = quantizer_scale_code;
 
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
/* make sure base.quantizer_scale is valid */
base.quantizer_scale = ld->quantizer_scale;
}
 
/* motion vectors */
 
 
/* ISO/IEC 13818-2 section 6.3.17.2: Motion vectors */
 
/* decode forward motion vectors */
if ((*macroblock_type & MACROBLOCK_MOTION_FORWARD)
|| ((*macroblock_type & MACROBLOCK_INTRA)
&& concealment_motion_vectors))
{
if (ld->MPEG2_Flag)
motion_vectors(PMV,dmvector,motion_vertical_field_select,
0,motion_vector_count,mv_format,f_code[0][0]-1,f_code[0][1]-1,
dmv,mvscale);
else
motion_vector(PMV[0][0],dmvector,
forward_f_code-1,forward_f_code-1,0,0,full_pel_forward_vector);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
/* decode backward motion vectors */
if (*macroblock_type & MACROBLOCK_MOTION_BACKWARD)
{
if (ld->MPEG2_Flag)
motion_vectors(PMV,dmvector,motion_vertical_field_select,
1,motion_vector_count,mv_format,f_code[1][0]-1,f_code[1][1]-1,0,
mvscale);
else
motion_vector(PMV[0][1],dmvector,
backward_f_code-1,backward_f_code-1,0,0,full_pel_backward_vector);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
if ((*macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
Flush_Buffer(1); /* remove marker_bit */
 
if (base.scalable_mode==SC_DP && base.priority_breakpoint==3)
ld = &enhan;
 
/* macroblock_pattern */
/* ISO/IEC 13818-2 section 6.3.17.4: Coded block pattern */
if (*macroblock_type & MACROBLOCK_PATTERN)
{
coded_block_pattern = Get_coded_block_pattern();
 
if (chroma_format==CHROMA422)
{
/* coded_block_pattern_1 */
coded_block_pattern = (coded_block_pattern<<2) | Get_Bits(2);
 
#ifdef TRACE
if (Trace_Flag)
{
printf("coded_block_pattern_1: ");
Print_Bits(coded_block_pattern,2,2);
printf(" (%d)\n",coded_block_pattern&3);
}
#endif /* TRACE */
}
else if (chroma_format==CHROMA444)
{
/* coded_block_pattern_2 */
coded_block_pattern = (coded_block_pattern<<6) | Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
printf("coded_block_pattern_2: ");
Print_Bits(coded_block_pattern,6,6);
printf(" (%d)\n",coded_block_pattern&63);
}
#endif /* TRACE */
}
}
else
coded_block_pattern = (*macroblock_type & MACROBLOCK_INTRA) ?
(1<<block_count)-1 : 0;
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
/* decode blocks */
for (comp=0; comp<block_count; comp++)
{
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
Clear_Block(comp);
 
if (coded_block_pattern & (1<<(block_count-1-comp)))
{
if (*macroblock_type & MACROBLOCK_INTRA)
{
if (ld->MPEG2_Flag)
Decode_MPEG2_Intra_Block(comp,dc_dct_pred);
else
Decode_MPEG1_Intra_Block(comp,dc_dct_pred);
}
else
{
if (ld->MPEG2_Flag)
Decode_MPEG2_Non_Intra_Block(comp);
else
Decode_MPEG1_Non_Intra_Block(comp);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
}
}
 
if(picture_coding_type==D_TYPE)
{
/* remove end_of_macroblock (always 1, prevents startcode emulation) */
/* ISO/IEC 11172-2 section 2.4.2.7 and 2.4.3.6 */
marker_bit("D picture end_of_macroblock bit");
}
 
/* reset intra_dc predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
if (!(*macroblock_type & MACROBLOCK_INTRA))
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
 
/* reset motion vector predictors */
if ((*macroblock_type & MACROBLOCK_INTRA) && !concealment_motion_vectors)
{
/* intra mb without concealment motion vectors */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
}
 
/* special "No_MC" macroblock_type case */
/* ISO/IEC 13818-2 section 7.6.3.5: Prediction in P pictures */
if ((picture_coding_type==P_TYPE)
&& !(*macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_INTRA)))
{
/* non-intra mb without forward mv in a P picture */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
 
/* derive motion_type */
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes, frame_motion_type */
if (picture_structure==FRAME_PICTURE)
*motion_type = MC_FRAME;
else
{
*motion_type = MC_FIELD;
/* predict from field of same parity */
motion_vertical_field_select[0][0] = (picture_structure==BOTTOM_FIELD);
}
}
 
if (*stwclass==4)
{
/* purely spatially predicted macroblock */
/* ISO/IEC 13818-2 section 7.7.5.1: Resetting motion vector predictions */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
}
 
/* successfully decoded macroblock */
return(1);
 
} /* decode_macroblock */
 
 
/advdemos/branches/advdemos/mpeg2/spatial.doc
0,0 → 1,154
The following changes have been made to debug spatial scalability:
 
gethdr.c
--------
 
Temporal_reference is used to compute the frame number of each frame,
named true_framenum. The periodic reset at each GOP header as well as
the wrap of temporal_reference at 1024 cause a base value
temp_ref_base to be incremented accordingly.
 
spatscal.c
----------
 
getspatref()
 
A potential problem: Variable char fname[32] was dimensioned
statically and too small.
 
true_framenum is used instead of lower_layer_temporal_reference to
determine the lower layer frame to be read for spatial prediction.
 
The verification of lower_layer_temporal_reference is not possible
since the temporal reference values that have been encoded into the
base layer bitstream are not available to the enhancement layer
decoder.
 
Since there is no decoder timing information available, the rules on
which frames can legally be used as spatial prediction frames cannot
be checked.
 
Lower layer frames are read field-wise or frame-wise, depending on the
lower_layer_progressive_frame flag. Consistency between layers is
checked since the file format for frame and field pictures differs.
 
Note that the base layer decoder must not use the -f option to enforce
frame-wise storage.
 
Note further that only yuv image format (option -o0) is supported as
input format.
 
spatpred()
 
The code for the various combinations of llprog_frame, llfieldsel and
prog_frame has been completed and verified with the tceh_conf23
bitstream that uses all permissive combinations.
 
 
getpic.c
--------
 
A small bug when storing an I- or P-frame: The prog_frame flag that
the decoder knows when storing the oldrefframe belongs to the current
refframe. Therefore the old value of the flag needs to be memorized.
 
 
store.c
-------
 
A potential problem: the filename variables char outname[32],
tmpname[32] are statically dimensioned and quite small.
 
 
The concept of time in this video decoder software
--------------------------------------------------
 
When decoding a non-scalable bitstream, the frame number (i.e.
temporal position) of the current I- or P-frame can be derived
implicitly from the number of preceding B-frames after they have been
decoded. Therefore the temporal_reference entry in the picture header
is somewhat redundant and does not necessarily have to be evaluated in
the decoding process.
 
Decoding of the enhancement layer of a spatial scalable hierarchy,
however, requires to know the temporal position of each frame at the
instant when it is decoded, since data from a lower layer reference
frame has to be incorporated.
 
In the architecture of this video-only decoder decoding of a spatial
scalable hierarchy of bitstreams is done by calling mpeg2decode once
for the base layer bitstream and a second time for the enhancement
layer bitstream, indicating where the decoded base layer frames can be
found (option -s<filename>).
 
Here the concept of time is only present in the form of frame numbers.
Therefore spatial scalable bitstream hierarchies can only be handled
under the assumption that base and enhancement layer bitstreams are
decoded to image sequences where corresponding images of both layers
have identical frame numbers.
 
More specifically this means that base and enhancement layer
bitstreams must contain video with the same frame rate. Furthermore
only the temporally coincident frame of the base layer can be accessed
for spatial prediction by the enhancement layer decoder, since it is
not possible to resolve unambiguously the lower_layer_temporal_reference
which is meant to further specify the lower layer reference frame.
 
======================== SPATIAL.DOC ========================0
 
Decoding a spatial scalable hierarchy of bitstreams
---------------------------------------------------
 
With this video-only decoder decoding of a spatial scalable hierarchy
of bitstreams is done by calling mpeg2decode once for the base layer
bitstream and a second time for the enhancement layer bitstream,
indicating where the decoded base layer frames can be found
(using option -s and supplying <spatial base filename>).
 
mpeg2decode -r -o0 base.mpg base%d%c
mpeg2decode -r -o0 -f -s base%d%c enh.mpg enh%d
 
Note that the base layer decoder must not use the -f option to enforce
frame-wise storage.
 
Note further that only yuv image format (option -o0) is supported as
input format.
 
 
Timing / layer synchronisation in this video decoder software
-------------------------------------------------------------
 
When decoding a non-scalable bitstream, the frame number (i.e.
temporal position) of the current I- or P-frame can be derived
implicitly from the number of preceding B-frames after they have been
decoded. Therefore the temporal_reference entry in the picture header
is somewhat redundant and does not necessarily have to be evaluated in
the decoding process.
 
Decoding of the enhancement layer of a spatial scalable hierarchy,
however, requires to know the temporal position of each frame at the
instant when it is decoded, since data from a lower layer reference
frame has to be incorporated.
 
The concept of time is only present in the form of frame numbers.
Therefore spatial scalable bitstream hierarchies can only be handled
under the assumption that base and enhancement layer bitstreams are
decoded to image sequences where corresponding images of both layers
have identical frame numbers.
 
More specifically this means that base and enhancement layer
bitstreams must contain video with the same frame rate. Furthermore
only the temporally coincident frame of the base layer can be accessed
for spatial prediction by the enhancement layer decoder, since it is
not possible to resolve unambiguously the lower_layer_temporal_reference
which is meant to further specify the lower layer reference frame.
 
Lower layer frames are read field-wise or frame-wise, depending on the
lower_layer_progressive_frame flag. Consistency between layers in this
respect is checked since the file format for frame and field pictures
differs.
 
 
 
 
 
/advdemos/branches/advdemos/mpeg2/idctref.c
0,0 → 1,108
/* Reference_IDCT.c, Inverse Discrete Fourier Transform, double precision */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* Perform IEEE 1180 reference (64-bit floating point, separable 8x1
* direct matrix multiply) Inverse Discrete Cosine Transform
*/
 
 
/* Here we use math.h to generate constants. Compiler results may
vary a little */
 
#include <math.h>
 
#include "config.h"
 
#ifndef PI
# ifdef M_PI
# define PI M_PI
# else
# define PI 3.14159265358979323846
# endif
#endif
 
/* global declarations */
void Initialize_Fast_IDCTref _ANSI_ARGS_((void));
void Reference_IDCT _ANSI_ARGS_((short *block));
 
/* private data */
 
/* cosine transform matrix for 8x1 IDCT */
static double c[8][8];
 
/* initialize DCT coefficient matrix */
 
void Initialize_Reference_IDCT()
{
int freq, time;
double scale;
 
for (freq=0; freq < 8; freq++)
{
scale = (freq == 0) ? sqrt(0.125) : 0.5;
for (time=0; time<8; time++)
c[freq][time] = scale*cos((PI/8.0)*freq*(time + 0.5));
}
}
 
/* perform IDCT matrix multiply for 8x8 coefficient block */
 
void Reference_IDCT(block)
short *block;
{
int i, j, k, v;
double partial_product;
double tmp[64];
 
for (i=0; i<8; i++)
for (j=0; j<8; j++)
{
partial_product = 0.0;
 
for (k=0; k<8; k++)
partial_product+= c[k][j]*block[8*i+k];
 
tmp[8*i+j] = partial_product;
}
 
/* Transpose operation is integrated into address mapping by switching
loop order of i and j */
 
for (j=0; j<8; j++)
for (i=0; i<8; i++)
{
partial_product = 0.0;
 
for (k=0; k<8; k++)
partial_product+= c[k][i]*tmp[8*k+j];
 
v = (int) floor(partial_product+0.5);
block[8*i+j] = (v<-256) ? -256 : ((v>255) ? 255 : v);
}
}
/advdemos/branches/advdemos/mpeg2/test.m2v
0,0 → 1,73
³€#ú 0µ‚µ#²MPEG-2 Verification Sequence
¸_¿l@
+Öߧâȧ@¥EJ_‹s6WKXT%• æÐöý$Lµ}iÑG•Â×Çi”@Bí-»’e´aà?{reLRÃùí–D7!GidÞ+fJ–€E +4ãQ#l&ØP8{iªì˳Õ*@«NÅZ؞UȲ©d‹iQ±­Ñ V÷<?'‰Ð¿Š\lU%’À-) ªUk­KèLC a°ä&¶‹t < AMm-¬ÃM!,P“ɨ­n¡0*ùC‚À‰YVìR‚Š<ó&ÁVÄ.SÂÀûfɀS՚’!£éç!Gs²–ÖR£ÍÚCXáÔæó©UÒÏA瞣ì)»‹¶ê 
+8£Ûä[ê©MëÙ@ªù-ƒaV*µ§¬ …H¡v*žÕÈ°øð9BcfÙdž©R’ŽC›VͶŸŒuV?2K<Û
+môxAÈóõ
+ƒÛ›»6C6„(h cÙ Ë ¯ü£hb—|—×Ԑ5‡´7Ñ*y­AÕ–ƒÐåD2µ»M±< ‹áæ2cjÍÞ"ÚJ$”ï؇P¹@ó”åhÛ­ãËf–\Bèß ¦ì\*—e¨PXW†·SgžU4Þ6Ä:D€5­íy… ™ÂÚ6’èÈTnº[Djo˜ùÁnæÎ+½Ý©J&¨ÂgídXPæôÿzñ'ÚoÒ¾EI
+––dßJُ}ÙÜR]­ëVhé$ƒ[©[ˆs2¦ÍÉf.ÑäʉT–Är­m2š²Ñò­µhm +
+³VCÀy$0±¤Ú¥y¡AL»%ô°aGB‚t¶ù1£›ê›¼š”àD!BÔ`ÚXbÙ `B©ò7J¿Ö⏔>éÔl7e£(û
+æ鷺¨²TP&FÁ2¸`JÑ£|Cɍ×v)r(Ö
+µ«Á†ãï–q
+ƒŠROŽ6šZJZ]¡'ÐÚ
+¯º¡Á/‰cz(L{yÿ}®PíûY·#•.Ëi:¥€DÝt¦jˆ60SÌçT‘3qç¦L ¥RÆÖæfU§\ñŽ´6î¶',»k|֐›õñ>>MMï:tåîË%à¥ØùlB†8ûÛ÷ÖóÆÏÆñlHf™-§@Œ
+oÏù–¶ÐÖôÞÈúM×ò.[N)fÉõŠØ}a9MZNF©úvÀü¸”6DK(`E=³]6–X–.ȶŒy¨°¤9¸½~p¢ÉãV’¡MÝÄï](7^m5Nñ¬©u¼q(íÆ­ìòÍëiÃY¢` ۇ^™G@–õNô§QOÈßt¿L°üø6„ÝjµOºøPÂ;Y졛Ÿ-ù?¥(û¼µÝ×òÙìñîn 
+š›˜d++Só>¶ãì¦ç?hù|e–7ä:ÀFVúßÀ!?D\L¢¾æD»²–O?JoŒŠ¦@GÿšÇ8uµ¿9¸rK[í<=N3¥gÐüvÏÖñr,ˆ«‡·šQFÑ(õn3s¥»œû æé–~¯:ú¶ùãËm©u=¿Ð"äþëàvpF²­æ}-¾‰…]67˜›m³$
+Hsy1
+âςe$7<)¹©Ííá}´fç9T¢›ó¥ûgnÑ=åá“Ö{ù@Jw k|O þ\*-6wtôÖMéu€;ù. ^3m o=ÀQ‚Z¾&{·#ÈMû§µJ2ãÛôkTe˜¬±C+£y–ßt‹…“öOc[ÈMÂF¨Ë~ÝҀòñ±°q C«»Fñà€ZúÏF/K·àœÐ`ÿö½¾¼‚40zò÷8X:Îۃ¸}½Ø‹•4Ÿ&’µÍ®CåúÌhcxb8{öµ#=;Â>À @\‡æH¹œU7Æ·”ÆÒo–­ú [§:%'Yð Eƒ‡áu¾VGÉö™«&:õq\g….©[žSr Š9¹¬'D-|[ñ@ãªïŸœ°>A–ßµ“ßîéœ8@¡‹j©·»T†ß–ˆûžýŠ–oÿ¯s`°q„Ùëc~˜Êz/š‹`©‡šT™ nh@ xÔFÄ[ <3Õ¿tF7âRfðE”`K|„RýŠÈýBYÅDSߢÐc|ÔBÿ®žð×¾*Üô<)®þu7âEÛ2­ç~y”àÉ»¨_8;0Cõ|M9¼¤q­æÒ[z¡@…þ"r!7¨1
+nÒf¼!‚k°z G”À"£óßo•Ù؊…”}ômbêÉCç|ßiæäJŽr/è$qÀB¶—ìËՉ…VpòÃË°)¼Ž’]o£oäbˑJÒ!(*Ž¤¶é ‘ᐈ .9aMõûÎQ’H6aë
+¡zÜøTkh{!ùB1¸T‘K ‡þ©U¸¯A{vÌo¹âj‘m…1<[Íw&!2;ŠYð)T±íxYcÛ¯èà¦ø̔šO¶QƝ™dZXŠûK•܋ɹ<ä1Ðí—Yéu
+kue… ñ}RÙaU£
+¼ŒpbQʉüƒÎäøÀş׀ӏ9GWÀàYFlÂÜøðbÿý„àwˆ¢G‘9„g€Ð–<Ï_"wƒðq´7
+dG7xÀD(åšÉ°aÁ`"€j¸6ÿ€h¼È Ȑ4ø{ž}|Àv ÷€Øã8Ÿ @Z ÐÞð6Ø `85‘þ8èÀ9¨nà¾çp*$®õÌ qª€À, ¡¿‘ÀjÒúà@-à6 _ÿ™Cwx €óŸHv`l~x“˜ˆú;‹)ÅՄ¤µÛ
+ÎØðât ÿþ(pát7õƒP€G,s€ÈžO¨ÔÂ)Š´qÔµCÇвQš8¦4â¶Á¯¨_€òÙñ
+õðfÿòp˜v8\ ßþ°5°°³mæèWáÊ$8…—Ð |G4ÀÓÿàGG™¿³Ãˆø:è÷KLÙFƒP³ì© :<0%c&Z›
+ª 7«=”ÈXÀʾ2’²·È7Ô4MðL‚`’
+Ó¦ÔK©V•H@?o•,1¾œ¦‰Ç7Q8G '™‘=őXq¯œÄ§Ç‘€9ÀjeœOàÇQò¸ê\ø¥l©R¡a@QÍ ½ˆ£èññV¡ÛªuJU-Ú*ÙOéFúo’o«hœ`˜% ‘ˆ%¡[1áafð<Öàg
+Käx
+höd ž¨›°êã7ôšÖcÀÛVn {j¹š~e
+BCà ÉxGîmé £àpú
+_UžÖêh‰íùüG±:©*Ê ù±¹¶ à jØ<Ѐ ¼UoÓcÍ4J–c#Àа•¦lGð €
+pwà"aPД9áî €ñà>€P ÿA¿áTM•®•ï>Y=ï¨1B«h ÚV,Qжó@|ß^f@6څÂPpI>À_‘’ŒWl9húAa®X .Ð`-=C
+)ÖÀ|Á†¢ävËרMã¬h%dÏ·b7´v„½ Ò ‚
+éã~# ø¿ÄÎ.U¤ŸèNcŋ%"-SÖÙ©?Ñ
+¢u…Ž0]ôÎ<Œ¨ªy æ€éÄÁ :É¢^¬Z"¹Ù0œAËóàaIc*°gkР½½ˆ0º}úÀb€GBu„ÀjbyQi*INm¡¢ÊAÏóÑ ¡‰úá–Éʵ¬wÖã…Ñ;AÇ@à5æûK›Ÿ‹R'ùtN0ŒÁ€†€äd–R_n΋NC{›øb¾à¼áƒ\hxޅFQ9ÃçÐox{HPÓÿiD€ý?@áõ·
\ No newline at end of file
/advdemos/branches/advdemos/mpeg2/getbits.c
0,0 → 1,202
/* getbits.c, bit level routines */
 
/*
* All modifications (mpeg2decode -> mpeg2play) are
* Copyright (C) 1996, Stefan Eckart. All Rights Reserved.
*/
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
 
#include "config.h"
#include "global.h"
 
/* initialize buffer, call once before first getbits or showbits */
 
void Initialize_Buffer()
{
ld->Incnt = 0;
ld->Rdptr = ld->Rdbfr + 2048;
ld->Rdmax = ld->Rdptr;
 
#ifdef VERIFY
/* only the verifier uses this particular bit counter
* Bitcnt keeps track of the current parser position with respect
* to the video elementary stream being decoded, regardless
* of whether or not it is wrapped within a systems layer stream
*/
ld->Bitcnt = 0;
#endif
 
ld->Bfr = 0;
Flush_Buffer(0); /* fills valid data into bfr */
}
 
void Fill_Buffer()
{
int Buffer_Level;
 
Buffer_Level = read(ld->Infile,ld->Rdbfr,2048);
ld->Rdptr = ld->Rdbfr;
 
if (System_Stream_Flag)
ld->Rdmax -= 2048;
 
/* end of the bitstream file */
if (Buffer_Level < 2048)
{
/* just to be safe */
if (Buffer_Level < 0)
Buffer_Level = 0;
 
/* pad until the next to the next 32-bit word boundary */
while (Buffer_Level & 3)
ld->Rdbfr[Buffer_Level++] = 0;
 
/* pad the buffer with sequence end codes */
while (Buffer_Level < 2048)
{
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>24;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>16;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>8;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE&0xff;
}
}
}
 
 
/* MPEG-1 system layer demultiplexer */
 
int Get_Byte()
{
while(ld->Rdptr >= ld->Rdbfr+2048)
{
read(ld->Infile,ld->Rdbfr,2048);
ld->Rdptr -= 2048;
ld->Rdmax -= 2048;
}
return *ld->Rdptr++;
}
 
/* extract a 16-bit word from the bitstream buffer */
int Get_Word()
{
int Val;
 
Val = Get_Byte();
return (Val<<8) | Get_Byte();
}
 
 
/* return next n bits (right adjusted) without advancing */
 
unsigned int Show_Bits(N)
int N;
{
return ld->Bfr >> (32-N);
}
 
 
/* return next bit (could be made faster than Get_Bits(1)) */
 
unsigned int Get_Bits1()
{
return Get_Bits(1);
}
 
 
/* advance by n bits */
 
void Flush_Buffer(N)
int N;
{
int Incnt;
 
ld->Bfr <<= N;
 
Incnt = ld->Incnt -= N;
 
if (Incnt <= 24)
{
if (System_Stream_Flag && (ld->Rdptr >= ld->Rdmax-4))
{
do
{
if (ld->Rdptr >= ld->Rdmax)
Next_Packet();
ld->Bfr |= Get_Byte() << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
else if (ld->Rdptr < ld->Rdbfr+2044)
{
do
{
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
else
{
do
{
if (ld->Rdptr >= ld->Rdbfr+2048)
Fill_Buffer();
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
ld->Incnt = Incnt;
}
 
#ifdef VERIFY
ld->Bitcnt += N;
#endif /* VERIFY */
 
}
 
 
/* return next n bits (right adjusted) */
 
unsigned int Get_Bits(N)
int N;
{
unsigned int Val;
 
Val = Show_Bits(N);
Flush_Buffer(N);
 
return Val;
}
 
/advdemos/branches/advdemos/mpeg2/initfile.c
0,0 → 1,256
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
/*
* CVS : $Id: initfile.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
*
* File: $File$
* Revision: $Revision: 1.1.1.1 $
* Last update: $Date: 2004-05-24 17:54:50 $
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/rr.h"
#include "modules/cbs.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
#include "modules/pi.h"
#include "modules/pc.h"
#include "modules/srp.h"
#include "modules/npp.h"
#include "modules/nop.h"
#include "modules/nopm.h"
 
#include "drivers/keyb.h"
 
#include <trace/trace.h>
#include <trace/queues.h>
 
#include <fs/bdevinit.h>
#include <fs/fsinit.h>
#include <fs/bdev.h>
 
 
/*+ sysyem tick in us +*/
#define TICK 1000
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
extern int __register_sub_init_prologue(void);
extern int __register_sub_init(void);
 
__register_sub_init_prologue();
 
EDF_register_level(EDF_ENABLE_ALL);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
CBS_register_level(CBS_ENABLE_ALL, 0);
dummy_register_level();
 
SEM_register_module();
 
CABS_register_module();
 
PI_register_module();
PC_register_module();
NPP_register_module();
SRP_register_module();
NOP_register_module();
NOPM_register_module();
 
__register_sub_init();
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
KEYB_PARMS keyb = BASE_KEYB;
extern int __bdev_sub_init(void);
extern int __fs_sub_init(void);
extern void ctrlc_exit(KEY_EVT *k);
HARTPORT_init();
keyb_def_ctrlC(keyb, ctrlc_exit);
KEYB_init(&keyb);
 
__bdev_sub_init();
__fs_sub_init();
__call_main__(mb);
 
return (void *)0;
}
 
#define PSCANSCHED 1
#define NOTRACE
 
int __register_sub_init_prologue(void)
{
#ifndef NOTRACE
int id;
 
TRC_init_phase1(NULL);
trc_register_fixed_queue();
id=trc_create_queue(TRC_FIXED_QUEUE,NULL);
trc_trace_class(TRC_CLASS_USER);
trc_assign_class_to_queue(TRC_CLASS_USER,id);
#endif
return 0;
}
 
int __register_sub_init(void)
{
#if defined(EDFSCHED)
extern void BD_EDF_register_module(void);
BD_EDF_register_module();
#elif defined(PSCANSCHED)
extern void BD_PSCAN_register_module(void);
BD_PSCAN_register_module();
#endif
return 0;
}
 
dev_t root_device=-1;
dev_t temp_device=-1;
 
int choose_root_callback(dev_t dev,u_int8_t fs)
{
if (fs==FS_MSDOS) return dev;
return -1;
}
 
int choose_temp_callback(__dev_t dev,__uint8_t fs)
{
static int flag=0;
if (fs==FS_MSDOS) {
if (flag) return dev;
flag=1;
}
return -1;
}
 
int __bdev_sub_init(void)
{
BDEV_PARMS bdev=BASE_BDEV;
bdev_def_showinfo(bdev,FALSE);
bdev_init(&bdev);
 
root_device=bdev_scan_devices(choose_root_callback);
if (root_device<0) {
cprintf("can't find root device to mount on /!!!\n");
sys_end();
return -1;
}
 
/*
temp_device=bdev_scan_devices(choose_temp_callback);
if (temp_device<0) {
cprintf("can't find a filesystem to mount on /TEMP!!!\n");
}
*/
return 0;
}
 
 
int __fs_sub_init(void)
{
extern int libc_initialize(void);
FILESYSTEM_PARMS fs=BASE_FILESYSTEM;
struct mount_opts opts;
// int res;
filesystem_def_rootdevice(fs,root_device);
filesystem_def_fs(fs,FS_MSDOS);
filesystem_def_showinfo(fs,FALSE);
filesystem_def_options(fs,opts);
 
memset(&opts,0,sizeof(struct mount_opts));
opts.flags=MOUNT_FLAG_RW;
 
 
filesystem_init(&fs);
 
/*
if (temp_device>=0) {
memset(&opts,0,sizeof(struct mount_opts));
opts.flags=MOUNT_FLAG_RW;
res=mount(temp_device,FS_MSDOS,"/TEMP",&opts);
if (res!=0) {
cprintf("can't mount XXX on /TEMP (errno: %i)\n",errno);
} else
cprintf("mounted /TEMP rw\n");
}
*/
libc_initialize();
 
#ifndef NOTRACE
TRC_init_phase2();
#endif
return 0;
}
 
void ctrlc_exit(KEY_EVT *k)
{
extern void dump_sem_table(void);
extern void dump_nop_table(void);
#ifndef NOGRX
grx_close();
#endif
cprintf("CTRL-C pressed!\n");
sys_end();
}
 
 
 
 
 
 
 
/advdemos/branches/advdemos/mpeg2/store.ori
0,0 → 1,576
/* store.c, picture output routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void store_one _ANSI_ARGS_((char *outname, unsigned char *src[],
int offset, int incr, int height));
static void store_yuv _ANSI_ARGS_((char *outname, unsigned char *src[],
int offset, int incr, int height));
static void store_sif _ANSI_ARGS_((char *outname, unsigned char *src[],
int offset, int incr, int height));
static void store_ppm_tga _ANSI_ARGS_((char *outname, unsigned char *src[],
int offset, int incr, int height, int tgaflag));
static void store_yuv1 _ANSI_ARGS_((char *name, unsigned char *src,
int offset, int incr, int width, int height));
static void putbyte _ANSI_ARGS_((int c));
static void putword _ANSI_ARGS_((int w));
static void conv422to444 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
static void conv420to422 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
 
#define OBFRSIZE 4096
static unsigned char obfr[OBFRSIZE];
static unsigned char *optr;
static int outfile;
 
/*
* store a picture as either one frame or two fields
*/
void Write_Frame(src,frame)
unsigned char *src[];
int frame;
{
char outname[FILENAME_LENGTH];
 
if (progressive_sequence || progressive_frame || Frame_Store_Flag)
{
/* progressive */
sprintf(outname,Output_Picture_Filename,frame,'f');
store_one(outname,src,0,Coded_Picture_Width,vertical_size);
}
else
{
/* interlaced */
sprintf(outname,Output_Picture_Filename,frame,'a');
store_one(outname,src,0,Coded_Picture_Width<<1,vertical_size>>1);
 
sprintf(outname,Output_Picture_Filename,frame,'b');
store_one(outname,src,
Coded_Picture_Width,Coded_Picture_Width<<1,vertical_size>>1);
}
}
 
/*
* store one frame or one field
*/
static void store_one(outname,src,offset,incr,height)
char *outname;
unsigned char *src[];
int offset, incr, height;
{
switch (Output_Type)
{
case T_YUV:
store_yuv(outname,src,offset,incr,height);
break;
case T_SIF:
store_sif(outname,src,offset,incr,height);
break;
case T_TGA:
store_ppm_tga(outname,src,offset,incr,height,1);
break;
case T_PPM:
store_ppm_tga(outname,src,offset,incr,height,0);
break;
#ifdef DISPLAY
case T_X11:
dither(src);
break;
#endif
default:
break;
}
}
 
/* separate headerless files for y, u and v */
static void store_yuv(outname,src,offset,incr,height)
char *outname;
unsigned char *src[];
int offset,incr,height;
{
int hsize;
char tmpname[FILENAME_LENGTH];
 
hsize = horizontal_size;
 
sprintf(tmpname,"%s.Y",outname);
store_yuv1(tmpname,src[0],offset,incr,hsize,height);
 
if (chroma_format!=CHROMA444)
{
offset>>=1; incr>>=1; hsize>>=1;
}
 
if (chroma_format==CHROMA420)
{
height>>=1;
}
 
sprintf(tmpname,"%s.U",outname);
store_yuv1(tmpname,src[1],offset,incr,hsize,height);
 
sprintf(tmpname,"%s.V",outname);
store_yuv1(tmpname,src[2],offset,incr,hsize,height);
}
 
/* auxiliary routine */
static void store_yuv1(name,src,offset,incr,width,height)
char *name;
unsigned char *src;
int offset,incr,width,height;
{
int i, j;
unsigned char *p;
 
if (!Quiet_Flag)
fprintf(stderr,"saving %s\n",name);
 
if ((outfile = open(name,O_CREAT|O_TRUNC|O_WRONLY|O_BINARY,0666))==-1)
{
sprintf(Error_Text,"Couldn't create %s\n",name);
Error(Error_Text);
}
 
optr=obfr;
 
for (i=0; i<height; i++)
{
p = src + offset + incr*i;
for (j=0; j<width; j++)
putbyte(*p++);
}
 
if (optr!=obfr)
write(outfile,obfr,optr-obfr);
 
close(outfile);
}
 
/*
* store as headerless file in U,Y,V,Y format
*/
static void store_sif (outname,src,offset,incr,height)
char *outname;
unsigned char *src[];
int offset, incr, height;
{
int i,j;
unsigned char *py, *pu, *pv;
static unsigned char *u422, *v422;
 
if (chroma_format==CHROMA444)
Error("4:4:4 not supported for SIF format");
 
if (chroma_format==CHROMA422)
{
u422 = src[1];
v422 = src[2];
}
else
{
if (!u422)
{
if (!(u422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
if (!(v422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
}
conv420to422(src[1],u422);
conv420to422(src[2],v422);
}
 
strcat(outname,".SIF");
 
if (!Quiet_Flag)
fprintf(stderr,"saving %s\n",outname);
 
if ((outfile = open(outname,O_CREAT|O_TRUNC|O_WRONLY|O_BINARY,0666))==-1)
{
sprintf(Error_Text,"Couldn't create %s\n",outname);
Error(Error_Text);
}
 
optr = obfr;
 
for (i=0; i<height; i++)
{
py = src[0] + offset + incr*i;
pu = u422 + (offset>>1) + (incr>>1)*i;
pv = v422 + (offset>>1) + (incr>>1)*i;
 
for (j=0; j<horizontal_size; j+=2)
{
putbyte(*pu++);
putbyte(*py++);
putbyte(*pv++);
putbyte(*py++);
}
}
 
if (optr!=obfr)
write(outfile,obfr,optr-obfr);
 
close(outfile);
}
 
/*
* store as PPM (PBMPLUS) or uncompressed Truevision TGA ('Targa') file
*/
static void store_ppm_tga(outname,src,offset,incr,height,tgaflag)
char *outname;
unsigned char *src[];
int offset, incr, height;
int tgaflag;
{
int i, j;
int y, u, v, r, g, b;
int crv, cbu, cgu, cgv;
unsigned char *py, *pu, *pv;
static unsigned char tga24[14] = {0,0,2,0,0,0,0, 0,0,0,0,0,24,32};
char header[FILENAME_LENGTH];
static unsigned char *u422, *v422, *u444, *v444;
 
if (chroma_format==CHROMA444)
{
u444 = src[1];
v444 = src[2];
}
else
{
if (!u444)
{
if (chroma_format==CHROMA420)
{
if (!(u422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
if (!(v422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (!(u444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
 
if (!(v444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (chroma_format==CHROMA420)
{
conv420to422(src[1],u422);
conv420to422(src[2],v422);
conv422to444(u422,u444);
conv422to444(v422,v444);
}
else
{
conv422to444(src[1],u444);
conv422to444(src[2],v444);
}
}
 
strcat(outname,tgaflag ? ".tga" : ".ppm");
 
if (!Quiet_Flag)
fprintf(stderr,"saving %s\n",outname);
 
if ((outfile = open(outname,O_CREAT|O_TRUNC|O_WRONLY|O_BINARY,0666))==-1)
{
sprintf(Error_Text,"Couldn't create %s\n",outname);
Error(Error_Text);
}
 
optr = obfr;
 
if (tgaflag)
{
/* TGA header */
for (i=0; i<12; i++)
putbyte(tga24[i]);
 
putword(horizontal_size); putword(height);
putbyte(tga24[12]); putbyte(tga24[13]);
}
else
{
/* PPM header */
sprintf(header,"P6\n%d %d\n255\n",horizontal_size,height);
 
for (i=0; header[i]!=0; i++)
putbyte(header[i]);
}
 
/* matrix coefficients */
crv = Inverse_Table_6_9[matrix_coefficients][0];
cbu = Inverse_Table_6_9[matrix_coefficients][1];
cgu = Inverse_Table_6_9[matrix_coefficients][2];
cgv = Inverse_Table_6_9[matrix_coefficients][3];
for (i=0; i<height; i++)
{
py = src[0] + offset + incr*i;
pu = u444 + offset + incr*i;
pv = v444 + offset + incr*i;
 
for (j=0; j<horizontal_size; j++)
{
u = *pu++ - 128;
v = *pv++ - 128;
y = 76309 * (*py++ - 16); /* (255/219)*65536 */
r = Clip[(y + crv*v + 32768)>>16];
g = Clip[(y - cgu*u - cgv*v + 32768)>>16];
b = Clip[(y + cbu*u + 32786)>>16];
 
if (tgaflag)
{
putbyte(b); putbyte(g); putbyte(r);
}
else
{
putbyte(r); putbyte(g); putbyte(b);
}
}
}
 
if (optr!=obfr)
write(outfile,obfr,optr-obfr);
 
close(outfile);
}
 
static void putbyte(c)
int c;
{
*optr++ = c;
 
if (optr == obfr+OBFRSIZE)
{
write(outfile,obfr,OBFRSIZE);
optr = obfr;
}
}
 
static void putword(w)
int w;
{
putbyte(w); putbyte(w>>8);
}
 
/* horizontal 1:2 interpolation filter */
static void conv422to444(src,dst)
unsigned char *src,*dst;
{
int i, i2, w, j, im3, im2, im1, ip1, ip2, ip3;
 
w = Coded_Picture_Width>>1;
 
if (base.MPEG2_Flag)
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
i2 = i<<1;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 21 0 -52 0 159 256 159 0 -52 0 21 */
/* even samples (0 0 256 0 0) */
dst[i2] = src[i];
 
/* odd samples (21 -52 159 159 -52 21) */
dst[i2+1] = Clip[(int)(21*(src[im2]+src[ip3])
-52*(src[im1]+src[ip2])
+159*(src[i]+src[ip1])+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
else
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
 
i2 = i<<1;
im3 = (i<3) ? 0 : i-3;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
dst[i2] = Clip[(int)( 5*src[im3]
-21*src[im2]
+70*src[im1]
+228*src[i]
-37*src[ip1]
+11*src[ip2]+128)>>8];
 
dst[i2+1] = Clip[(int)( 5*src[ip3]
-21*src[ip2]
+70*src[ip1]
+228*src[i]
-37*src[im1]
+11*src[im2]+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
}
 
/* vertical 1:2 interpolation filter */
static void conv420to422(src,dst)
unsigned char *src,*dst;
{
int w, h, i, j, j2;
int jm6, jm5, jm4, jm3, jm2, jm1, jp1, jp2, jp3, jp4, jp5, jp6, jp7;
 
w = Coded_Picture_Width>>1;
h = Coded_Picture_Height>>1;
 
if (progressive_frame)
{
/* intra frame */
for (i=0; i<w; i++)
{
for (j=0; j<h; j++)
{
j2 = j<<1;
jm3 = (j<3) ? 0 : j-3;
jm2 = (j<2) ? 0 : j-2;
jm1 = (j<1) ? 0 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp2 = (j<h-2) ? j+2 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
/* New FIR filter coefficients (*256): 3 -16 67 227 -32 7 */
dst[w*j2] = Clip[(int)( 3*src[w*jm3]
-16*src[w*jm2]
+67*src[w*jm1]
+227*src[w*j]
-32*src[w*jp1]
+7*src[w*jp2]+128)>>8];
 
dst[w*(j2+1)] = Clip[(int)( 3*src[w*jp3]
-16*src[w*jp2]
+67*src[w*jp1]
+227*src[w*j]
-32*src[w*jm1]
+7*src[w*jm2]+128)>>8];
}
src++;
dst++;
}
}
else
{
/* intra field */
for (i=0; i<w; i++)
{
for (j=0; j<h; j+=2)
{
j2 = j<<1;
 
/* top field */
jm6 = (j<6) ? 0 : j-6;
jm4 = (j<4) ? 0 : j-4;
jm2 = (j<2) ? 0 : j-2;
jp2 = (j<h-2) ? j+2 : h-2;
jp4 = (j<h-4) ? j+4 : h-2;
jp6 = (j<h-6) ? j+6 : h-2;
 
/* Polyphase FIR filter coefficients (*256): 2 -10 35 242 -18 5 */
/* New polyphase FIR filter coefficients (*256): 1 -7 30 248 -21 5 */
dst[w*j2] = Clip[(int)( 1*src[w*jm6]
-7*src[w*jm4]
+30*src[w*jm2]
+248*src[w*j]
-21*src[w*jp2]
+5*src[w*jp4]+128)>>8];
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+2)] = Clip[(int)( 7*src[w*jm4]
-35*src[w*jm2]
+194*src[w*j]
+110*src[w*jp2]
-24*src[w*jp4]
+4*src[w*jp6]+128)>>8];
 
/* bottom field */
jm5 = (j<5) ? 1 : j-5;
jm3 = (j<3) ? 1 : j-3;
jm1 = (j<1) ? 1 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
jp5 = (j<h-5) ? j+5 : h-1;
jp7 = (j<h-7) ? j+7 : h-1;
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+1)] = Clip[(int)( 7*src[w*jp5]
-35*src[w*jp3]
+194*src[w*jp1]
+110*src[w*jm1]
-24*src[w*jm3]
+4*src[w*jm5]+128)>>8];
 
dst[w*(j2+3)] = Clip[(int)( 1*src[w*jp7]
-7*src[w*jp5]
+30*src[w*jp3]
+248*src[w*jp1]
-21*src[w*jm1]
+5*src[w*jm3]+128)>>8];
}
src++;
dst++;
}
}
}
/advdemos/branches/advdemos/mpeg2/verify.c
0,0 → 1,303
/* verify.c
*
* Bitstream verification routines
*
*
*/
#ifdef VERIFY
 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <math.h> /* needed for ceil() */
 
#include "config.h"
#include "global.h"
 
/* #define DEBUG */
#ifdef DEBUG
#define PC
#endif
 
#ifdef PC
#include <conio.h> /* needed for getch() */
#endif /* PC */
 
/*
Check picture headers: due to the VBV definition of picture data,
this routine must be called immediately before any picture data
is parsed. (before the first slice start code, including any slice
start code stuffing).
*/
 
 
static void Check_VBV_Delay _ANSI_ARGS_((int Bitstream_Framenum, int Sequence_Framenum));
 
 
void Check_Headers(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum;
int Sequence_Framenum;
{
 
 
if((!low_delay)&&(vbv_delay!=0)&&(vbv_delay!=0xFFFF))
Check_VBV_Delay(Bitstream_Framenum, Sequence_Framenum);
 
/* clear out the header tracking variables so we have an accurate
count next time */
Clear_Verify_Headers();
}
 
 
 
/*
* Verify vbv_delay value in picture header
* (low_delay==1 checks not implemented. this does not exhaustively test all
* possibilities suggested in ISO/IEC 13818-2 Annex C. It only checks
* for constant rate streams)
*
* Q:how do we tell a variable rate stream from a constant rate stream anyway?
* it's not as simple as vbv_delay==0xFFFF, since we need meaningful
* vbv_delay values to calculate the piecewise rate in the first place!
*
* Also: no special provisions at the beginning or end of a sequence
*/
 
static void Check_VBV_Delay(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum;
int Sequence_Framenum;
{
double B; /* buffer size */
double Bn; /* buffer fullness for picture n */
double R; /* bitrate */
double I; /* time interval (t[n+1] - t[n]) */
double T; /* inverse of the frame rate (frame period) */
 
int d;
int internal_vbv_delay;
static int previous_IorP_picture_structure;
static int previous_IorP_repeat_first_field;
static int previous_IorP_top_field_first;
static int previous_vbv_delay;
static int previous_bitstream_position;
 
static double previous_Bn;
static double E; /* maximum quantization error or mismatch */
 
 
if((Sequence_Framenum==0)&&(!Second_Field))
{ /* first coded picture of sequence */
 
R = bit_rate;
 
/* the initial buffer occupancy is taken on faith
that is, we believe what is transmitted in the first coded picture header
to be the true/actual buffer occupancy */
Bn = (R * (double) vbv_delay) / 90000.0;
B = 16 * 1024 * vbv_buffer_size;
 
/* maximum quantization error in bitrate (bit_rate_value is quantized/
rounded-up to units of 400 bits/sec as per ISO/IEC 13818-2
section 6.3.3 */
E = (400.0/frame_rate) + 400;
 
#ifdef DEBUG
printf("vbv_buffer_size (B) = %.0f, Bn=%f, E=%f, \nbitrate=%f, vbv_delay=%d frame_rate=%f\n",
B, Bn, E, bit_rate, vbv_delay, frame_rate);
#endif
 
}
else /* not the first coded picture of sequence */
{
 
/* derive the interval (I). The interval tells us how many constant rate bits
* will have been downloaded to the buffer during the current picture period
*
* interval assumes that:
* 1. whilst we are decoding the current I or P picture, we are displaying
* the previous I or P picture which was stored in the reorder
* buffer (pointed to by forward_reference_frame in this implementation)
*
* 2. B pictures are output ("displayed") at the time when they are decoded
*
*/
 
if(progressive_sequence) /* Annex C.9 (progressive_sequence==1, low_delay==0) */
{
 
T = 1/frame_rate; /* inverse of the frame rate (frame period) */
 
if(picture_coding_type==B_TYPE)
{
if(repeat_first_field==1)
{
if(top_field_first==1)
I = T*3; /* three frame periods */
else
I = T*2; /* two frame periods */
}
else
I = T; /* one frame period */
}
else /* P or I frame */
{
if(previous_IorP_repeat_first_field==1)
{
if(previous_IorP_top_field_first==1)
I = 3*T;
else
I = 2*T;
}
else
I = T;
}
}
else /* Annex C.11 (progressive_sequence==0, low_delay==0) */
{
T = 1/(2*frame_rate); /* inverse of two times the frame rate (field period) */
 
if(picture_coding_type==B_TYPE)
{
if(picture_structure==FRAME_PICTURE)
{
if(repeat_first_field==0)
I = 2*T; /* two field periods */
else
I = 3*T; /* three field periods */
}
else /* B field */
{
I = T; /* one field period */
}
}
else /* I or P picture */
{
if(picture_structure==FRAME_PICTURE)
{
if(previous_IorP_repeat_first_field==0)
I = 2*T;
else
I = 3*T;
}
else
{
if(Second_Field==0) /* first field of current frame */
I = T;
else /* second field of current frame */
{
/* formula: previous I or P display period (2*T or 3*T) minus the
very recent decode period (T) of the first field of the current
frame */
 
if(previous_IorP_picture_structure!=FRAME_PICTURE
|| previous_IorP_repeat_first_field==0)
I = 2*T - T; /* a net of one field period */
else if(previous_IorP_picture_structure==FRAME_PICTURE
&& previous_IorP_repeat_first_field==1)
I = 3*T - T; /* a net of two field periods */
}
}
}
}
 
/* derive coded size of previous picture */
d = ld->Bitcnt - previous_bitstream_position;
 
/* Rate = Distance/Time */
 
/* piecewise constant rate (variable rate stream) calculation
* R = ((double) d /((previous_vbv_delay - vbv_delay)/90000 + I));
*/
 
R = bit_rate;
 
/* compute buffer fullness just before removing picture n
*
* Bn = previous_Bn + (I*R) - d; (recursive formula)
*
* where:
*
* n is the current picture
*
* Bn is the buffer fullness for the current picture
*
* previous_Bn is the buffer fullness of the previous picture
*
* (I*R ) is the bits accumulated during the current picture
* period
*
* d is the number of bits removed during the decoding of the
* previous picture
*/
 
Bn = previous_Bn + (I*R) - d;
 
/* compute internally derived vbv_delay (rouding up with ceil()) */
internal_vbv_delay = (int) ceil((90000 * Bn / bit_rate));
 
#ifdef DEBUG
printf("\nvbv_delay: internal=%d, bitstream=%d\n", internal_vbv_delay, vbv_delay);
printf("Bn=%f, prevBn=%f, I=%f, R=%f, d=%d\n", Bn, previous_Bn, I, R, d);
printf("frame(%d), pictstruct(%d), picttype(%d)\n", Sequence_Framenum,
picture_structure, picture_coding_type);
 
/* report error */
if(internal_vbv_delay != vbv_delay)
{
printf("WARNING: internal_vbv_delay(%d) != vbv_delay(%d)\n",
internal_vbv_delay, vbv_delay);
}
#endif
 
} /* not the first coded picture of sequence */
 
 
#ifdef PC
getch();
#endif /* PC */
/* update generic tracking variables */
previous_bitstream_position = ld->Bitcnt ;
previous_vbv_delay = vbv_delay;
previous_Bn = Bn;
 
/* reference picture: reordered/delayed output picture */
if(picture_coding_type!=B_TYPE)
{
previous_IorP_repeat_first_field = repeat_first_field;
previous_IorP_top_field_first = top_field_first;
previous_IorP_picture_structure = picture_structure;
}
 
}
 
 
 
/* variables to keep track of the occurance of redundant headers between pictures */
void Clear_Verify_Headers()
{
verify_sequence_header = 0;
verify_group_of_pictures_header = 0;
verify_picture_header = 0;
verify_slice_header = 0;
verify_sequence_extension = 0;
verify_sequence_display_extension = 0;
verify_quant_matrix_extension = 0;
verify_sequence_scalable_extension = 0;
verify_picture_display_extension = 0;
verify_picture_coding_extension = 0;
verify_picture_spatial_scalable_extension = 0;
verify_picture_temporal_scalable_extension = 0;
verify_copyright_extension = 0;
}
 
#endif /* VERIFY */
 
/advdemos/branches/advdemos/mpeg2/motion.c
0,0 → 1,236
/* motion.c, motion vector decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void decode_motion_vector _ANSI_ARGS_((int *pred, int r_size, int motion_code,
int motion_residualesidual, int full_pel_vector));
 
/* ISO/IEC 13818-2 sections 6.2.5.2, 6.3.17.2, and 7.6.3: Motion vectors */
void motion_vectors(PMV,dmvector,
motion_vertical_field_select,s,motion_vector_count,mv_format,h_r_size,v_r_size,dmv,mvscale)
int PMV[2][2][2];
int dmvector[2];
int motion_vertical_field_select[2][2];
int s, motion_vector_count, mv_format, h_r_size, v_r_size, dmv, mvscale;
{
if (motion_vector_count==1)
{
if (mv_format==MV_FIELD && !dmv)
{
motion_vertical_field_select[1][s] = motion_vertical_field_select[0][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
printf("motion_vertical_field_select[][%d] (%d): %d\n",s,
motion_vertical_field_select[0][s],motion_vertical_field_select[0][s]);
}
#endif /* TRACE */
}
 
motion_vector(PMV[0][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
 
/* update other motion vector predictors */
PMV[1][s][0] = PMV[0][s][0];
PMV[1][s][1] = PMV[0][s][1];
}
else
{
motion_vertical_field_select[0][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
printf("motion_vertical_field_select[0][%d] (%d): %d\n",s,
motion_vertical_field_select[0][s],motion_vertical_field_select[0][s]);
}
#endif /* TRACE */
motion_vector(PMV[0][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
 
motion_vertical_field_select[1][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
printf("motion_vertical_field_select[1][%d] (%d): %d\n",s,
motion_vertical_field_select[1][s],motion_vertical_field_select[1][s]);
}
#endif /* TRACE */
motion_vector(PMV[1][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
}
}
 
/* get and decode motion vector and differential motion vector
for one prediction */
void motion_vector(PMV,dmvector,
h_r_size,v_r_size,dmv,mvscale,full_pel_vector)
int *PMV;
int *dmvector;
int h_r_size;
int v_r_size;
int dmv; /* MPEG-2 only: get differential motion vectors */
int mvscale; /* MPEG-2 only: field vector in frame pic */
int full_pel_vector; /* MPEG-1 only */
{
int motion_code, motion_residual;
 
/* horizontal component */
/* ISO/IEC 13818-2 Table B-10 */
motion_code = Get_motion_code();
 
motion_residual = (h_r_size!=0 && motion_code!=0) ? Get_Bits(h_r_size) : 0;
 
#ifdef TRACE
if (Trace_Flag)
{
if (h_r_size!=0 && motion_code!=0)
{
printf("motion_residual (");
Print_Bits(motion_residual,h_r_size,h_r_size);
printf("): %d\n",motion_residual);
}
}
#endif /* TRACE */
 
 
decode_motion_vector(&PMV[0],h_r_size,motion_code,motion_residual,full_pel_vector);
 
if (dmv)
dmvector[0] = Get_dmvector();
 
 
/* vertical component */
motion_code = Get_motion_code();
motion_residual = (v_r_size!=0 && motion_code!=0) ? Get_Bits(v_r_size) : 0;
 
#ifdef TRACE
if (Trace_Flag)
{
if (v_r_size!=0 && motion_code!=0)
{
printf("motion_residual (");
Print_Bits(motion_residual,v_r_size,v_r_size);
printf("): %d\n",motion_residual);
}
}
#endif /* TRACE */
 
if (mvscale)
PMV[1] >>= 1; /* DIV 2 */
 
decode_motion_vector(&PMV[1],v_r_size,motion_code,motion_residual,full_pel_vector);
 
if (mvscale)
PMV[1] <<= 1;
 
if (dmv)
dmvector[1] = Get_dmvector();
 
#ifdef TRACE
if (Trace_Flag)
printf("PMV = %d,%d\n",PMV[0],PMV[1]);
#endif /* TRACE */
}
 
/* calculate motion vector component */
/* ISO/IEC 13818-2 section 7.6.3.1: Decoding the motion vectors */
/* Note: the arithmetic here is more elegant than that which is shown
in 7.6.3.1. The end results (PMV[][][]) should, however, be the same. */
 
static void decode_motion_vector(pred,r_size,motion_code,motion_residual,full_pel_vector)
int *pred;
int r_size, motion_code, motion_residual;
int full_pel_vector; /* MPEG-1 (ISO/IEC 11172-1) support */
{
int lim, vec;
 
lim = 16<<r_size;
vec = full_pel_vector ? (*pred >> 1) : (*pred);
 
if (motion_code>0)
{
vec+= ((motion_code-1)<<r_size) + motion_residual + 1;
if (vec>=lim)
vec-= lim + lim;
}
else if (motion_code<0)
{
vec-= ((-motion_code-1)<<r_size) + motion_residual + 1;
if (vec<-lim)
vec+= lim + lim;
}
*pred = full_pel_vector ? (vec<<1) : vec;
}
 
 
/* ISO/IEC 13818-2 section 7.6.3.6: Dual prime additional arithmetic */
void Dual_Prime_Arithmetic(DMV,dmvector,mvx,mvy)
int DMV[][2];
int *dmvector; /* differential motion vector */
int mvx, mvy; /* decoded mv components (always in field format) */
{
if (picture_structure==FRAME_PICTURE)
{
if (top_field_first)
{
/* vector for prediction of top field from bottom field */
DMV[0][0] = ((mvx +(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((mvy +(mvy>0))>>1) + dmvector[1] - 1;
 
/* vector for prediction of bottom field from top field */
DMV[1][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
DMV[1][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] + 1;
}
else
{
/* vector for prediction of top field from bottom field */
DMV[0][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] - 1;
 
/* vector for prediction of bottom field from top field */
DMV[1][0] = ((mvx +(mvx>0))>>1) + dmvector[0];
DMV[1][1] = ((mvy +(mvy>0))>>1) + dmvector[1] + 1;
}
}
else
{
/* vector for prediction from field of opposite 'parity' */
DMV[0][0] = ((mvx+(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((mvy+(mvy>0))>>1) + dmvector[1];
 
/* correct for vertical field shift */
if (picture_structure==TOP_FIELD)
DMV[0][1]--;
else
DMV[0][1]++;
}
}
 
/advdemos/branches/advdemos/mpeg2/global.h
0,0 → 1,515
/* global.h, global variables */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "mpeg2dec.h"
 
/* choose between declaration (GLOBAL undefined)
* and definition (GLOBAL defined)
* GLOBAL is defined in exactly one file mpeg2dec.c)
*/
 
#ifndef GLOBAL
#define EXTERN extern
#else
#define EXTERN
#endif
 
/* prototypes of global functions */
/* readpic.c */
void Substitute_Frame_Buffer _ANSI_ARGS_ ((int bitstream_framenum,
int sequence_framenum));
 
/* Get_Bits.c */
void Initialize_Buffer _ANSI_ARGS_((void));
void Fill_Buffer _ANSI_ARGS_((void));
unsigned int Show_Bits _ANSI_ARGS_((int n));
unsigned int Get_Bits1 _ANSI_ARGS_((void));
void Flush_Buffer _ANSI_ARGS_((int n));
unsigned int Get_Bits _ANSI_ARGS_((int n));
int Get_Byte _ANSI_ARGS_((void));
int Get_Word _ANSI_ARGS_((void));
 
/* systems.c */
void Next_Packet _ANSI_ARGS_((void));
int Get_Long _ANSI_ARGS_((void));
void Flush_Buffer32 _ANSI_ARGS_((void));
unsigned int Get_Bits32 _ANSI_ARGS_((void));
 
 
/* getblk.c */
void Decode_MPEG1_Intra_Block _ANSI_ARGS_((int comp, int dc_dct_pred[]));
void Decode_MPEG1_Non_Intra_Block _ANSI_ARGS_((int comp));
void Decode_MPEG2_Intra_Block _ANSI_ARGS_((int comp, int dc_dct_pred[]));
void Decode_MPEG2_Non_Intra_Block _ANSI_ARGS_((int comp));
 
/* gethdr.c */
int Get_Hdr _ANSI_ARGS_((void));
void next_start_code _ANSI_ARGS_((void));
int slice_header _ANSI_ARGS_((void));
void marker_bit _ANSI_ARGS_((char *text));
 
/* getpic.c */
void Decode_Picture _ANSI_ARGS_((int bitstream_framenum,
int sequence_framenum));
void Output_Last_Frame_of_Sequence _ANSI_ARGS_((int framenum));
 
/* getvlc.c */
int Get_macroblock_type _ANSI_ARGS_((void));
int Get_motion_code _ANSI_ARGS_((void));
int Get_dmvector _ANSI_ARGS_((void));
int Get_coded_block_pattern _ANSI_ARGS_((void));
int Get_macroblock_address_increment _ANSI_ARGS_((void));
int Get_Luma_DC_dct_diff _ANSI_ARGS_((void));
int Get_Chroma_DC_dct_diff _ANSI_ARGS_((void));
 
/* idct.c */
void Fast_IDCT _ANSI_ARGS_((short *block));
void Initialize_Fast_IDCT _ANSI_ARGS_((void));
 
/* Reference_IDCT.c */
void Initialize_Reference_IDCT _ANSI_ARGS_((void));
void Reference_IDCT _ANSI_ARGS_((short *block));
 
/* motion.c */
void motion_vectors _ANSI_ARGS_((int PMV[2][2][2], int dmvector[2],
int motion_vertical_field_select[2][2], int s, int motion_vector_count,
int mv_format, int h_r_size, int v_r_size, int dmv, int mvscale));
void motion_vector _ANSI_ARGS_((int *PMV, int *dmvector,
int h_r_size, int v_r_size, int dmv, int mvscale, int full_pel_vector));
void Dual_Prime_Arithmetic _ANSI_ARGS_((int DMV[][2], int *dmvector, int mvx, int mvy));
 
/* mpeg2dec.c */
void Error _ANSI_ARGS_((char *text));
void Warning _ANSI_ARGS_((char *text));
void Print_Bits _ANSI_ARGS_((int code, int bits, int len));
 
/* recon.c */
void form_predictions _ANSI_ARGS_((int bx, int by, int macroblock_type,
int motion_type, int PMV[2][2][2], int motion_vertical_field_select[2][2],
int dmvector[2], int stwtype));
 
/* spatscal.c */
void Spatial_Prediction _ANSI_ARGS_((void));
 
/* store.c */
void Write_Frame _ANSI_ARGS_((unsigned char *src[], int frame));
 
#ifdef DISPLAY
/* display.c */
void Initialize_Display_Process _ANSI_ARGS_((char *name));
void Terminate_Display_Process _ANSI_ARGS_((void));
void Display_Second_Field _ANSI_ARGS_((void));
void dither _ANSI_ARGS_((unsigned char *src[]));
void Initialize_Dither_Matrix _ANSI_ARGS_((void));
#endif
 
/* global variables */
 
EXTERN char Version[]
#ifdef GLOBAL
="mpeg2decode V1.2a, 96/07/19"
#endif
;
 
EXTERN char Author[]
#ifdef GLOBAL
="(C) 1996, MPEG Software Simulation Group"
#endif
;
 
 
/* zig-zag and alternate scan patterns */
EXTERN unsigned char scan[2][64]
#ifdef GLOBAL
=
{
{ /* 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
},
{ /* 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
}
}
#endif
;
 
/* default intra quantization matrix */
EXTERN unsigned char default_intra_quantizer_matrix[64]
#ifdef GLOBAL
=
{
8, 16, 19, 22, 26, 27, 29, 34,
16, 16, 22, 24, 27, 29, 34, 37,
19, 22, 26, 27, 29, 34, 34, 38,
22, 22, 26, 27, 29, 34, 37, 40,
22, 26, 27, 29, 32, 35, 40, 48,
26, 27, 29, 32, 35, 40, 48, 58,
26, 27, 29, 34, 38, 46, 56, 69,
27, 29, 35, 38, 46, 56, 69, 83
}
#endif
;
 
/* non-linear quantization coefficient table */
EXTERN unsigned char Non_Linear_quantizer_scale[32]
#ifdef GLOBAL
=
{
0, 1, 2, 3, 4, 5, 6, 7,
8,10,12,14,16,18,20,22,
24,28,32,36,40,44,48,52,
56,64,72,80,88,96,104,112
}
#endif
;
 
/* color space conversion coefficients
* for YCbCr -> RGB mapping
*
* entries are {crv,cbu,cgu,cgv}
*
* crv=(255/224)*65536*(1-cr)/0.5
* cbu=(255/224)*65536*(1-cb)/0.5
* cgu=(255/224)*65536*(cb/cg)*(1-cb)/0.5
* cgv=(255/224)*65536*(cr/cg)*(1-cr)/0.5
*
* where Y=cr*R+cg*G+cb*B (cr+cg+cb=1)
*/
 
/* ISO/IEC 13818-2 section 6.3.6 sequence_display_extension() */
 
EXTERN int Inverse_Table_6_9[8][4]
#ifdef GLOBAL
=
{
{117504, 138453, 13954, 34903}, /* no sequence_display_extension */
{117504, 138453, 13954, 34903}, /* ITU-R Rec. 709 (1990) */
{104597, 132201, 25675, 53279}, /* unspecified */
{104597, 132201, 25675, 53279}, /* reserved */
{104448, 132798, 24759, 53109}, /* FCC */
{104597, 132201, 25675, 53279}, /* ITU-R Rec. 624-4 System B, G */
{104597, 132201, 25675, 53279}, /* SMPTE 170M */
{117579, 136230, 16907, 35559} /* SMPTE 240M (1987) */
}
#endif
;
 
 
 
 
 
/* output types (Output_Type) */
#define T_YUV 0
#define T_SIF 1
#define T_TGA 2
#define T_PPM 3
#define T_X11 4
#define T_X11HIQ 5
 
/* decoder operation control variables */
EXTERN int Output_Type;
EXTERN int hiQdither;
 
/* decoder operation control flags */
EXTERN int Quiet_Flag;
EXTERN int Trace_Flag;
EXTERN int Fault_Flag;
EXTERN int Verbose_Flag;
EXTERN int Two_Streams;
EXTERN int Spatial_Flag;
EXTERN int Reference_IDCT_Flag;
EXTERN int Frame_Store_Flag;
EXTERN int System_Stream_Flag;
EXTERN int Display_Progressive_Flag;
EXTERN int Ersatz_Flag;
EXTERN int Big_Picture_Flag;
EXTERN int Verify_Flag;
EXTERN int Stats_Flag;
EXTERN int User_Data_Flag;
EXTERN int Main_Bitstream_Flag;
 
 
/* filenames */
EXTERN char *Output_Picture_Filename;
EXTERN char *Substitute_Picture_Filename;
EXTERN char *Main_Bitstream_Filename;
EXTERN char *Enhancement_Layer_Bitstream_Filename;
 
 
/* buffers for multiuse purposes */
EXTERN char Error_Text[256];
EXTERN unsigned char *Clip;
 
/* pointers to generic picture buffers */
EXTERN unsigned char *backward_reference_frame[3];
EXTERN unsigned char *forward_reference_frame[3];
 
EXTERN unsigned char *auxframe[3];
EXTERN unsigned char *current_frame[3];
EXTERN unsigned char *substitute_frame[3];
 
 
/* pointers to scalability picture buffers */
EXTERN unsigned char *llframe0[3];
EXTERN unsigned char *llframe1[3];
 
EXTERN short *lltmp;
EXTERN char *Lower_Layer_Picture_Filename;
 
 
 
 
/* non-normative variables derived from normative elements */
EXTERN int Coded_Picture_Width;
EXTERN int Coded_Picture_Height;
EXTERN int Chroma_Width;
EXTERN int Chroma_Height;
EXTERN int block_count;
EXTERN int Second_Field;
EXTERN int profile, level;
 
/* normative derived variables (as per ISO/IEC 13818-2) */
EXTERN int horizontal_size;
EXTERN int vertical_size;
EXTERN int mb_width;
EXTERN int mb_height;
EXTERN double bit_rate;
EXTERN double frame_rate;
 
 
 
/* headers */
 
/* ISO/IEC 13818-2 section 6.2.2.1: sequence_header() */
EXTERN int aspect_ratio_information;
EXTERN int frame_rate_code;
EXTERN int bit_rate_value;
EXTERN int vbv_buffer_size;
EXTERN int constrained_parameters_flag;
 
/* ISO/IEC 13818-2 section 6.2.2.3: sequence_extension() */
EXTERN int profile_and_level_indication;
EXTERN int progressive_sequence;
EXTERN int chroma_format;
EXTERN int low_delay;
EXTERN int frame_rate_extension_n;
EXTERN int frame_rate_extension_d;
 
/* ISO/IEC 13818-2 section 6.2.2.4: sequence_display_extension() */
EXTERN int video_format;
EXTERN int color_description;
EXTERN int color_primaries;
EXTERN int transfer_characteristics;
EXTERN int matrix_coefficients;
EXTERN int display_horizontal_size;
EXTERN int display_vertical_size;
 
/* ISO/IEC 13818-2 section 6.2.3: picture_header() */
EXTERN int temporal_reference;
EXTERN int picture_coding_type;
EXTERN int vbv_delay;
EXTERN int full_pel_forward_vector;
EXTERN int forward_f_code;
EXTERN int full_pel_backward_vector;
EXTERN int backward_f_code;
 
 
/* ISO/IEC 13818-2 section 6.2.3.1: picture_coding_extension() header */
EXTERN int f_code[2][2];
EXTERN int intra_dc_precision;
EXTERN int picture_structure;
EXTERN int top_field_first;
EXTERN int frame_pred_frame_dct;
EXTERN int concealment_motion_vectors;
 
EXTERN int intra_vlc_format;
 
EXTERN int repeat_first_field;
 
EXTERN int chroma_420_type;
EXTERN int progressive_frame;
EXTERN int composite_display_flag;
EXTERN int v_axis;
EXTERN int field_sequence;
EXTERN int sub_carrier;
EXTERN int burst_amplitude;
EXTERN int sub_carrier_phase;
 
 
 
/* ISO/IEC 13818-2 section 6.2.3.3: picture_display_extension() header */
EXTERN int frame_center_horizontal_offset[3];
EXTERN int frame_center_vertical_offset[3];
 
 
 
/* ISO/IEC 13818-2 section 6.2.2.5: sequence_scalable_extension() header */
EXTERN int layer_id;
EXTERN int lower_layer_prediction_horizontal_size;
EXTERN int lower_layer_prediction_vertical_size;
EXTERN int horizontal_subsampling_factor_m;
EXTERN int horizontal_subsampling_factor_n;
EXTERN int vertical_subsampling_factor_m;
EXTERN int vertical_subsampling_factor_n;
 
 
/* ISO/IEC 13818-2 section 6.2.3.5: picture_spatial_scalable_extension() header */
EXTERN int lower_layer_temporal_reference;
EXTERN int lower_layer_horizontal_offset;
EXTERN int lower_layer_vertical_offset;
EXTERN int spatial_temporal_weight_code_table_index;
EXTERN int lower_layer_progressive_frame;
EXTERN int lower_layer_deinterlaced_field_select;
 
 
 
 
 
 
/* ISO/IEC 13818-2 section 6.2.3.6: copyright_extension() header */
EXTERN int copyright_flag;
EXTERN int copyright_identifier;
EXTERN int original_or_copy;
EXTERN int copyright_number_1;
EXTERN int copyright_number_2;
EXTERN int copyright_number_3;
 
/* ISO/IEC 13818-2 section 6.2.2.6: group_of_pictures_header() */
EXTERN int drop_flag;
EXTERN int hour;
EXTERN int minute;
EXTERN int sec;
EXTERN int frame;
EXTERN int closed_gop;
EXTERN int broken_link;
 
 
 
/* layer specific variables (needed for SNR and DP scalability) */
EXTERN struct layer_data {
/* bit input */
int Infile;
unsigned char Rdbfr[2048];
unsigned char *Rdptr;
unsigned char Inbfr[16];
/* from mpeg2play */
unsigned int Bfr;
unsigned char *Rdmax;
int Incnt;
int Bitcnt;
/* sequence header and quant_matrix_extension() */
int intra_quantizer_matrix[64];
int non_intra_quantizer_matrix[64];
int chroma_intra_quantizer_matrix[64];
int chroma_non_intra_quantizer_matrix[64];
int load_intra_quantizer_matrix;
int load_non_intra_quantizer_matrix;
int load_chroma_intra_quantizer_matrix;
int load_chroma_non_intra_quantizer_matrix;
 
int MPEG2_Flag;
/* sequence scalable extension */
int scalable_mode;
/* picture coding extension */
int q_scale_type;
int alternate_scan;
/* picture spatial scalable extension */
int pict_scal;
/* slice/macroblock */
int priority_breakpoint;
int quantizer_scale;
int intra_slice;
short block[12][64];
} base, enhan, *ld;
 
 
 
#ifdef VERIFY
EXTERN int verify_sequence_header;
EXTERN int verify_group_of_pictures_header;
EXTERN int verify_picture_header;
EXTERN int verify_slice_header;
EXTERN int verify_sequence_extension;
EXTERN int verify_sequence_display_extension;
EXTERN int verify_quant_matrix_extension;
EXTERN int verify_sequence_scalable_extension;
EXTERN int verify_picture_display_extension;
EXTERN int verify_picture_coding_extension;
EXTERN int verify_picture_spatial_scalable_extension;
EXTERN int verify_picture_temporal_scalable_extension;
EXTERN int verify_copyright_extension;
#endif /* VERIFY */
 
 
EXTERN int Decode_Layer;
 
/* verify.c */
#ifdef VERIFY
void Check_Headers _ANSI_ARGS_((int Bitstream_Framenum, int Sequence_Framenum));
void Clear_Verify_Headers _ANSI_ARGS_((void));
#endif /* VERIFY */
 
 
EXTERN int global_MBA;
EXTERN int global_pic;
EXTERN int True_Framenum;
 
// PJ
 
void gvideo_init(void);
 
// Insertion/removal from display buffer
 
// number of preallocated frames
#define MAX_FRAMEBUF 20
 
struct framebuf_struct {
int n;
WORD *f;
struct framebuf_struct *next;
struct framebuf_struct *prev;
};
 
void Initialize_framebuf(int sz);
struct framebuf_struct *get_free_framebuf();
void insert_frame(struct framebuf_struct *f);
struct framebuf_struct *remove_frame();
void give_back_framebuf(struct framebuf_struct *f);
void init_jetcontrol(void);
 
 
 
 
/advdemos/branches/advdemos/mpeg2/recon.c
0,0 → 1,467
/* Predict.c, motion compensation routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void form_prediction _ANSI_ARGS_((unsigned char *src[], int sfield,
unsigned char *dst[], int dfield,
int lx, int lx2, int w, int h, int x, int y, int dx, int dy,
int average_flag));
 
static void form_component_prediction _ANSI_ARGS_((unsigned char *src, unsigned char *dst,
int lx, int lx2, int w, int h, int x, int y, int dx, int dy, int average_flag));
 
void form_predictions(bx,by,macroblock_type,motion_type,PMV,motion_vertical_field_select,dmvector,stwtype)
int bx, by;
int macroblock_type;
int motion_type;
int PMV[2][2][2], motion_vertical_field_select[2][2], dmvector[2];
int stwtype;
{
int currentfield;
unsigned char **predframe;
int DMV[2][2];
int stwtop, stwbot;
 
stwtop = stwtype%3; /* 0:temporal, 1:(spat+temp)/2, 2:spatial */
stwbot = stwtype/3;
 
if ((macroblock_type & MACROBLOCK_MOTION_FORWARD)
|| (picture_coding_type==P_TYPE))
{
if (picture_structure==FRAME_PICTURE)
{
if ((motion_type==MC_FRAME)
|| !(macroblock_type & MACROBLOCK_MOTION_FORWARD))
{
/* frame-based prediction (broken into top and bottom halves
for spatial scalability prediction purposes) */
if (stwtop<2)
form_prediction(forward_reference_frame,0,current_frame,0,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
 
if (stwbot<2)
form_prediction(forward_reference_frame,1,current_frame,1,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwbot);
}
else if (motion_type==MC_FIELD) /* field-based prediction */
{
/* top field prediction */
if (stwtop<2)
form_prediction(forward_reference_frame,motion_vertical_field_select[0][0],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[0][0][0],PMV[0][0][1]>>1,stwtop);
 
/* bottom field prediction */
if (stwbot<2)
form_prediction(forward_reference_frame,motion_vertical_field_select[1][0],
current_frame,1,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[1][0][0],PMV[1][0][1]>>1,stwbot);
}
else if (motion_type==MC_DMV) /* dual prime prediction */
{
/* calculate derived motion vectors */
Dual_Prime_Arithmetic(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]>>1);
 
if (stwtop<2)
{
/* predict top field from top field */
form_prediction(forward_reference_frame,0,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
PMV[0][0][0],PMV[0][0][1]>>1,0);
 
/* predict and add to top field from bottom field */
form_prediction(forward_reference_frame,1,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
DMV[0][0],DMV[0][1],1);
}
 
if (stwbot<2)
{
/* predict bottom field from bottom field */
form_prediction(forward_reference_frame,1,current_frame,1,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
PMV[0][0][0],PMV[0][0][1]>>1,0);
 
/* predict and add to bottom field from top field */
form_prediction(forward_reference_frame,0,current_frame,1,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
DMV[1][0],DMV[1][1],1);
}
}
else
/* invalid motion_type */
printf("invalid motion_type\n");
}
else /* TOP_FIELD or BOTTOM_FIELD */
{
/* field picture */
currentfield = (picture_structure==BOTTOM_FIELD);
 
/* determine which frame to use for prediction */
if ((picture_coding_type==P_TYPE) && Second_Field
&& (currentfield!=motion_vertical_field_select[0][0]))
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
if ((motion_type==MC_FIELD)
|| !(macroblock_type & MACROBLOCK_MOTION_FORWARD))
{
/* field-based prediction */
if (stwtop<2)
form_prediction(predframe,motion_vertical_field_select[0][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
}
else if (motion_type==MC_16X8)
{
if (stwtop<2)
{
form_prediction(predframe,motion_vertical_field_select[0][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
 
/* determine which frame to use for lower half prediction */
if ((picture_coding_type==P_TYPE) && Second_Field
&& (currentfield!=motion_vertical_field_select[1][0]))
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
form_prediction(predframe,motion_vertical_field_select[1][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by+8,
PMV[1][0][0],PMV[1][0][1],stwtop);
}
}
else if (motion_type==MC_DMV) /* dual prime prediction */
{
if (Second_Field)
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
/* calculate derived motion vectors */
Dual_Prime_Arithmetic(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]);
 
/* predict from field of same parity */
form_prediction(forward_reference_frame,currentfield,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
PMV[0][0][0],PMV[0][0][1],0);
 
/* predict from field of opposite parity */
form_prediction(predframe,!currentfield,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
DMV[0][0],DMV[0][1],1);
}
else
/* invalid motion_type */
printf("invalid motion_type\n");
}
stwtop = stwbot = 1;
}
 
if (macroblock_type & MACROBLOCK_MOTION_BACKWARD)
{
if (picture_structure==FRAME_PICTURE)
{
if (motion_type==MC_FRAME)
{
/* frame-based prediction */
if (stwtop<2)
form_prediction(backward_reference_frame,0,current_frame,0,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][1][0],PMV[0][1][1],stwtop);
 
if (stwbot<2)
form_prediction(backward_reference_frame,1,current_frame,1,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][1][0],PMV[0][1][1],stwbot);
}
else /* field-based prediction */
{
/* top field prediction */
if (stwtop<2)
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[0][1][0],PMV[0][1][1]>>1,stwtop);
 
/* bottom field prediction */
if (stwbot<2)
form_prediction(backward_reference_frame,motion_vertical_field_select[1][1],
current_frame,1,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[1][1][0],PMV[1][1][1]>>1,stwbot);
}
}
else /* TOP_FIELD or BOTTOM_FIELD */
{
/* field picture */
if (motion_type==MC_FIELD)
{
/* field-based prediction */
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,
bx,by,PMV[0][1][0],PMV[0][1][1],stwtop);
}
else if (motion_type==MC_16X8)
{
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by,PMV[0][1][0],PMV[0][1][1],stwtop);
 
form_prediction(backward_reference_frame,motion_vertical_field_select[1][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by+8,PMV[1][1][0],PMV[1][1][1],stwtop);
}
else
/* invalid motion_type */
printf("invalid motion_type\n");
}
}
}
 
static void form_prediction(src,sfield,dst,dfield,lx,lx2,w,h,x,y,dx,dy,average_flag)
unsigned char *src[]; /* prediction source buffer */
int sfield; /* prediction source field number (0 or 1) */
unsigned char *dst[]; /* prediction destination buffer */
int dfield; /* prediction destination field number (0 or 1)*/
int lx,lx2; /* line strides */
int w,h; /* prediction block/sub-block width, height */
int x,y; /* pixel co-ordinates of top-left sample in current MB */
int dx,dy; /* horizontal, vertical prediction address */
int average_flag; /* add prediction error to prediction ? */
{
/* Y */
form_component_prediction(src[0]+(sfield?lx2>>1:0),dst[0]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
 
if (chroma_format!=CHROMA444)
{
lx>>=1; lx2>>=1; w>>=1; x>>=1; dx/=2;
}
 
if (chroma_format==CHROMA420)
{
h>>=1; y>>=1; dy/=2;
}
 
/* Cb */
form_component_prediction(src[1]+(sfield?lx2>>1:0),dst[1]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
 
/* Cr */
form_component_prediction(src[2]+(sfield?lx2>>1:0),dst[2]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
}
 
/* ISO/IEC 13818-2 section 7.6.4: Forming predictions */
/* NOTE: the arithmetic below produces numerically equivalent results
* to 7.6.4, yet is more elegant. It differs in the following ways:
*
* 1. the vectors (dx, dy) are based on cartesian frame
* coordiantes along a half-pel grid (always positive numbers)
* In contrast, vector[r][s][t] are differential (with positive and
* negative values). As a result, deriving the integer vectors
* (int_vec[t]) from dx, dy is accomplished by a simple right shift.
*
* 2. Half pel flags (xh, yh) are equivalent to the LSB (Least
* Significant Bit) of the half-pel coordinates (dx,dy).
*
*
* NOTE: the work of combining predictions (ISO/IEC 13818-2 section 7.6.7)
* is distributed among several other stages. This is accomplished by
* folding line offsets into the source and destination (src,dst)
* addresses (note the call arguments to form_prediction() in Predict()),
* line stride variables lx and lx2, the block dimension variables (w,h),
* average_flag, and by the very order in which Predict() is called.
* This implementation design (implicitly different than the spec)
* was chosen for its elegance.
*/
 
static void form_component_prediction(src,dst,lx,lx2,w,h,x,y,dx,dy,average_flag)
unsigned char *src;
unsigned char *dst;
int lx; /* raster line increment */
int lx2;
int w,h;
int x,y;
int dx,dy;
int average_flag; /* flag that signals bi-directional or Dual-Prime
averaging (7.6.7.1 and 7.6.7.4). if average_flag==1,
a previously formed prediction has been stored in
pel_pred[] */
{
int xint; /* horizontal integer sample vector: analogous to int_vec[0] */
int yint; /* vertical integer sample vectors: analogous to int_vec[1] */
int xh; /* horizontal half sample flag: analogous to half_flag[0] */
int yh; /* vertical half sample flag: analogous to half_flag[1] */
int i, j, v;
unsigned char *s; /* source pointer: analogous to pel_ref[][] */
unsigned char *d; /* destination pointer: analogous to pel_pred[][] */
 
/* half pel scaling for integer vectors */
xint = dx>>1;
yint = dy>>1;
 
/* derive half pel flags */
xh = dx & 1;
yh = dy & 1;
 
/* compute the linear address of pel_ref[][] and pel_pred[][]
based on cartesian/raster cordinates provided */
s = src + lx*(y+yint) + x + xint;
d = dst + lx*y + x;
 
if (!xh && !yh) /* no horizontal nor vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i]+s[i];
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = s[i];
}
s+= lx2;
d+= lx2;
}
}
}
else if (!xh && yh) /* no horizontal but vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+lx]+1)>>1);
d[i]=(v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+lx]+1)>>1;
}
 
s+= lx2;
d+= lx2;
}
}
}
else if (xh && !yh) /* horizontal but no vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+1]+1)>>1);
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+1]+1)>>1;
}
 
s+= lx2;
d+= lx2;
}
}
}
else /* if (xh && yh) horizontal and vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2);
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2;
}
 
s+= lx2;
d+= lx2;
}
}
}
}
/advdemos/branches/advdemos/mpeg2/systems.c
0,0 → 1,200
/* systems.c, systems-specific routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
 
#include "config.h"
#include "global.h"
 
/* initialize buffer, call once before first getbits or showbits */
 
/* parse system layer, ignore everything we don't need */
void Next_Packet()
{
unsigned int code;
int l;
 
for(;;)
{
code = Get_Long();
 
/* remove system layer byte stuffing */
while ((code & 0xffffff00) != 0x100)
code = (code<<8) | Get_Byte();
 
switch(code)
{
case PACK_START_CODE: /* pack header */
/* skip pack header (system_clock_reference and mux_rate) */
ld->Rdptr += 8;
break;
case VIDEO_ELEMENTARY_STREAM:
code = Get_Word(); /* packet_length */
ld->Rdmax = ld->Rdptr + code;
 
code = Get_Byte();
 
if((code>>6)==0x02)
{
ld->Rdptr++;
code=Get_Byte(); /* parse PES_header_data_length */
ld->Rdptr+=code; /* advance pointer by PES_header_data_length */
printf("MPEG-2 PES packet\n");
return;
}
else if(code==0xff)
{
/* parse MPEG-1 packet header */
while((code=Get_Byte())== 0xFF);
}
/* stuffing bytes */
if(code>=0x40)
{
if(code>=0x80)
{
fprintf(stderr,"Error in packet header\n");
exit(1);
}
/* skip STD_buffer_scale */
ld->Rdptr++;
code = Get_Byte();
}
 
if(code>=0x30)
{
if(code>=0x40)
{
fprintf(stderr,"Error in packet header\n");
exit(1);
}
/* skip presentation and decoding time stamps */
ld->Rdptr += 9;
}
else if(code>=0x20)
{
/* skip presentation time stamps */
ld->Rdptr += 4;
}
else if(code!=0x0f)
{
fprintf(stderr,"Error in packet header\n");
exit(1);
}
return;
case ISO_END_CODE: /* end */
/* simulate a buffer full of sequence end codes */
l = 0;
while (l<2048)
{
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>24;
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>16;
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>8;
ld->Rdbfr[l++] = SEQUENCE_END_CODE&0xff;
}
ld->Rdptr = ld->Rdbfr;
ld->Rdmax = ld->Rdbfr + 2048;
return;
default:
if(code>=SYSTEM_START_CODE)
{
/* skip system headers and non-video packets*/
code = Get_Word();
ld->Rdptr += code;
}
else
{
fprintf(stderr,"Unexpected startcode %08x in system layer\n",code);
exit(1);
}
break;
}
}
}
 
 
 
void Flush_Buffer32()
{
int Incnt;
 
ld->Bfr = 0;
 
Incnt = ld->Incnt;
Incnt -= 32;
 
if (System_Stream_Flag && (ld->Rdptr >= ld->Rdmax-4))
{
while (Incnt <= 24)
{
if (ld->Rdptr >= ld->Rdmax)
Next_Packet();
ld->Bfr |= Get_Byte() << (24 - Incnt);
Incnt += 8;
}
}
else
{
while (Incnt <= 24)
{
if (ld->Rdptr >= ld->Rdbfr+2048)
Fill_Buffer();
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
}
ld->Incnt = Incnt;
 
#ifdef VERIFY
ld->Bitcnt += 32;
#endif /* VERIFY */
}
 
 
unsigned int Get_Bits32()
{
unsigned int l;
 
l = Show_Bits(32);
Flush_Buffer32();
 
return l;
}
 
 
int Get_Long()
{
int i;
 
i = Get_Word();
return (i<<16) | Get_Word();
}
 
 
/advdemos/branches/advdemos/mpeg2/subspic.c
0,0 → 1,392
/* #define DEBUG */
/* subspic.c, Frame buffer substitution routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes*/
static void Read_Frame _ANSI_ARGS_((char *filename,
unsigned char *frame_buffer[], int framenum));
static void Copy_Frame _ANSI_ARGS_((unsigned char *src, unsigned char *dst,
int width, int height, int parity, int incr));
static int Read_Components _ANSI_ARGS_ ((char *filename,
unsigned char *frame[3], int framenum));
static int Read_Component _ANSI_ARGS_ ((char *fname, unsigned char *frame,
int width, int height));
static int Extract_Components _ANSI_ARGS_ ((char *filename,
unsigned char *frame[3], int framenum));
 
 
/* substitute frame buffer routine */
void Substitute_Frame_Buffer (bitstream_framenum, sequence_framenum)
int bitstream_framenum;
int sequence_framenum;
{
/* static tracking variables */
static int previous_temporal_reference;
static int previous_bitstream_framenum;
static int previous_anchor_temporal_reference;
static int previous_anchor_bitstream_framenum;
static int previous_picture_coding_type;
static int bgate;
/* local temporary variables */
int substitute_display_framenum;
 
 
#ifdef DEBUG
printf("SUB: seq fn(%d) bitfn(%d) tempref(%d) picstr(%d) type(%d)\n",
sequence_framenum, bitstream_framenum, temporal_reference,
picture_structure, picture_coding_type);
#endif
 
/* we don't substitute at the first picture of a sequence */
if((sequence_framenum!=0)||(Second_Field))
{
/* only at the start of the frame */
if ((picture_structure==FRAME_PICTURE)||(!Second_Field))
{
if(picture_coding_type==P_TYPE)
{
/* the most recently decoded reference frame needs substituting */
substitute_display_framenum = bitstream_framenum - 1;
Read_Frame(Substitute_Picture_Filename, forward_reference_frame,
substitute_display_framenum);
}
/* only the first B frame in a consequitve set of B pictures
loads a substitute backward_reference_frame since all subsequent
B frames predict from the same reference pictures */
else if((picture_coding_type==B_TYPE)&&(bgate!=1))
{
substitute_display_framenum =
(previous_temporal_reference - temporal_reference)
+ bitstream_framenum - 1;
 
Read_Frame(Substitute_Picture_Filename, backward_reference_frame,
substitute_display_framenum);
}
} /* P fields can predict from the two most recently decoded fields, even
from the first field of the same frame being decoded */
else if(Second_Field && (picture_coding_type==P_TYPE))
{
/* our favourite case: the IP field picture pair */
if((previous_picture_coding_type==I_TYPE)&&(picture_coding_type==P_TYPE))
{
substitute_display_framenum = bitstream_framenum;
}
else /* our more generic P field picture pair */
{
substitute_display_framenum =
(temporal_reference - previous_anchor_temporal_reference)
+ bitstream_framenum - 1;
}
 
Read_Frame(Substitute_Picture_Filename, current_frame, substitute_display_framenum);
}
#ifdef DEBUG
else if((picture_coding_type!=B_TYPE)||(picture_coding_type!=D_TYPE))
{
printf("NO SUBS FOR THIS PICTURE\n");
}
#endif
}
 
 
/* set b gate so we don't redundantly load next time around */
if(picture_coding_type==B_TYPE)
bgate = 1;
else
bgate = 0;
 
/* update general tracking variables */
if((picture_structure==FRAME_PICTURE)||(!Second_Field))
{
previous_temporal_reference = temporal_reference;
previous_bitstream_framenum = bitstream_framenum;
}
/* update reference frame tracking variables */
if((picture_coding_type!=B_TYPE) &&
((picture_structure==FRAME_PICTURE)||Second_Field))
{
previous_anchor_temporal_reference = temporal_reference;
previous_anchor_bitstream_framenum = bitstream_framenum;
}
 
previous_picture_coding_type = picture_coding_type;
 
}
 
 
/* Note: fields are only read to serve as the same-frame reference for
a second field */
static void Read_Frame(fname,frame,framenum)
char *fname;
unsigned char *frame[];
int framenum;
{
int parity;
int rerr = 0;
int field_mode;
 
if(framenum<0)
printf("ERROR: framenum (%d) is less than zero\n", framenum);
 
 
if(Big_Picture_Flag)
rerr = Extract_Components(fname, substitute_frame, framenum);
else
rerr = Read_Components(fname, substitute_frame, framenum);
 
if(rerr!=0)
{
printf("was unable to substitute frame\n");
}
 
/* now copy to the appropriate buffer */
/* first field (which we are attempting to substitute) must be
of opposite field parity to the current one */
if((Second_Field)&&(picture_coding_type==P_TYPE))
{
parity = (picture_structure==TOP_FIELD ? 1:0);
field_mode = (picture_structure==FRAME_PICTURE ? 0:1);
}
else
{
/* Like frame structued pictures, B pictures only substitute an entire frame
since both fields always predict from the same frame (with respect
to forward/backwards directions) */
parity = 0;
field_mode = 0;
}
 
 
Copy_Frame(substitute_frame[0], frame[0], Coded_Picture_Width,
Coded_Picture_Height, parity, field_mode);
Copy_Frame(substitute_frame[1], frame[1], Chroma_Width, Chroma_Height,
parity, field_mode);
Copy_Frame(substitute_frame[2], frame[2], Chroma_Width, Chroma_Height,
parity, field_mode);
 
#ifdef VERBOSE
if(Verbose_Flag > NO_LAYER)
printf("substituted %s %d\n",
(field_mode ? (parity?"bottom field":"bottom field"):"frame"), framenum);
#endif
}
 
 
 
 
static int Read_Components(filename, frame, framenum)
char *filename;
unsigned char *frame[3];
int framenum;
{
int err = 0;
char outname[FILENAME_LENGTH];
char name[FILENAME_LENGTH];
 
sprintf(outname,filename,framenum);
 
 
sprintf(name,"%s.Y",outname);
err += Read_Component(name, frame[0], Coded_Picture_Width,
Coded_Picture_Height);
 
sprintf(name,"%s.U",outname);
err += Read_Component(name, frame[1], Chroma_Width, Chroma_Height);
 
sprintf(name,"%s.V",outname);
err += Read_Component(name, frame[2], Chroma_Width, Chroma_Height);
 
return(err);
}
 
 
static int Read_Component(Filename, Frame, Width, Height)
char *Filename;
unsigned char *Frame;
int Width;
int Height;
{
int Size;
int Bytes_Read;
int Infile;
 
Size = Width*Height;
 
#ifdef DEBUG
printf("SUBS: reading %s\n", filename);
#endif
 
if(!(Infile=open(Filename,O_RDONLY|O_BINARY))<0)
{
printf("ERROR: unable to open reference filename (%s)\n", Filename);
return(-1);
}
 
Bytes_Read = read(Infile, Frame, Size);
if(Bytes_Read!=Size)
{
printf("was able to read only %d bytes of %d of file %s\n",
Bytes_Read, Size, Filename);
}
close(Infile);
return(0);
}
 
 
/* optimization: do not open the big file each time. Open once at start
of decoder, and close at the very last frame */
 
/* Note: "big" files were used in E-mail exchanges almost exclusively by the
MPEG Committee's syntax validation and conformance ad-hoc groups from
the year 1993 until 1995 */
static int Extract_Components(filename, frame, framenum)
char *filename;
unsigned char *frame[3];
int framenum;
{
/* int err = 0; */
FILE *fd;
int line;
int size, offset;
 
 
if (!(fd = fopen(filename,"rb")))
{
sprintf(Error_Text,"Couldn't open %s\n",filename);
return(-1);
}
 
/* compute size of each frame (in bytes) */
size = (Coded_Picture_Width*Coded_Picture_Height);
 
if(chroma_format==CHROMA444)
size = (size * 3);
else if(chroma_format==CHROMA422)
size = (size * 2);
else if(chroma_format==CHROMA420)
size = ((size*3)>>1);
else
printf("ERROR: chroma_format (%d) not recognized\n", chroma_format);
 
 
/* compute distance into "big" file */
offset = size*framenum;
 
#ifdef DEBUG
printf("EXTRACTING: frame(%d) offset(%d), size (%d) from %s\n",
framenum, offset, size, filename);
#endif
 
/* seek to location in big file where desired frame begins */
/* note: this offset cannot exceed a few billion bytes due to the */
/* obvious limitations of 32-bit integers */
fseek(fd, offset, 0);
 
/* Y */
for (line=0; line<Coded_Picture_Height; line++)
{
fread(frame[0]+(line*Coded_Picture_Width),1,Coded_Picture_Width,fd);
}
 
/* Cb */
for (line=0; line<Chroma_Height; line++)
{
fread(frame[1]+(line*Chroma_Width),1,Chroma_Width,fd);
}
 
/* Cr */
for (line=0; line<Chroma_Height; line++)
{
fread(frame[2]+(line*Chroma_Width),1,Chroma_Width,fd);
}
 
 
fclose(fd);
return(0);
}
 
 
static void Copy_Frame(src, dst, width, height, parity, field_mode)
unsigned char *src;
unsigned char *dst;
int width;
int height;
int parity; /* field parity (top or bottom) to overwrite */
int field_mode; /* 0 = frame, 1 = field */
{
int row, col;
int s, d;
int incr;
 
s = d = 0;
 
#ifdef DEBUG
printf("COPYING (w=%d, h=%d, parity=%d, field_mode=%d)\n",
width,height,parity,field_mode);
#endif /* DEBUG */
 
if(field_mode)
{
incr = 2;
 
if(parity==0)
s += width;
}
else
{
incr = 1;
}
 
for(row=0; row<height; row+=incr)
{
for(col=0; col<width; col++)
{
dst[d+col] = src[s+col];
}
d += (width*incr);
s += (width*incr);
}
 
}
 
/advdemos/branches/advdemos/mpeg2/getblk.c
0,0 → 1,570
/* getblk.c, DCT block decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
 
 
/* defined in getvlc.h */
typedef struct {
char run, level, len;
} DCTtab;
 
extern DCTtab DCTtabfirst[],DCTtabnext[],DCTtab0[],DCTtab1[];
extern DCTtab DCTtab2[],DCTtab3[],DCTtab4[],DCTtab5[],DCTtab6[];
extern DCTtab DCTtab0a[],DCTtab1a[];
 
 
/* decode one intra coded MPEG-1 block */
 
void Decode_MPEG1_Intra_Block(comp,dc_dct_pred)
int comp;
int dc_dct_pred[];
{
int val, i, j, sign;
unsigned int code;
DCTtab *tab;
short *bp;
 
bp = ld->block[comp];
 
/* ISO/IEC 11172-2 section 2.4.3.7: Block layer. */
/* decode DC coefficients */
if (comp<4)
bp[0] = (dc_dct_pred[0]+=Get_Luma_DC_dct_diff()) << 3;
else if (comp==4)
bp[0] = (dc_dct_pred[1]+=Get_Chroma_DC_dct_diff()) << 3;
else
bp[0] = (dc_dct_pred[2]+=Get_Chroma_DC_dct_diff()) << 3;
 
if (Fault_Flag) return;
 
/* D-pictures do not contain AC coefficients */
if(picture_coding_type == D_TYPE)
return;
 
/* decode AC coefficients */
for (i=1; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
tab = &DCTtabnext[(code>>12)-4];
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
printf("invalid Huffman code in Decode_MPEG1_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
if (tab->run==64) /* end_of_block */
return;
 
if (tab->run==65) /* escape */
{
i+= Get_Bits(6);
 
val = Get_Bits(8);
if (val==0)
val = Get_Bits(8);
else if (val==128)
val = Get_Bits(8) - 256;
else if (val>128)
val -= 256;
 
if((sign = (val<0)))
val = -val;
}
else
{
i+= tab->run;
val = tab->level;
sign = Get_Bits(1);
}
 
if (i>=64)
{
if (!Quiet_Flag)
fprintf(stderr,"DCT coeff index (i) out of bounds (intra)\n");
Fault_Flag = 1;
return;
}
 
j = scan[ZIG_ZAG][i];
val = (val*ld->quantizer_scale*ld->intra_quantizer_matrix[j]) >> 3;
 
/* mismatch control ('oddification') */
if (val!=0) /* should always be true, but it's not guaranteed */
val = (val-1) | 1; /* equivalent to: if ((val&1)==0) val = val - 1; */
 
/* saturation */
if (!sign)
bp[j] = (val>2047) ? 2047 : val; /* positive */
else
bp[j] = (val>2048) ? -2048 : -val; /* negative */
}
}
 
 
/* decode one non-intra coded MPEG-1 block */
 
void Decode_MPEG1_Non_Intra_Block(comp)
int comp;
{
int val, i, j, sign;
unsigned int code;
DCTtab *tab;
short *bp;
 
bp = ld->block[comp];
 
/* decode AC coefficients */
for (i=0; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
{
if (i==0)
tab = &DCTtabfirst[(code>>12)-4];
else
tab = &DCTtabnext[(code>>12)-4];
}
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
printf("invalid Huffman code in Decode_MPEG1_Non_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
if (tab->run==64) /* end_of_block */
return;
 
if (tab->run==65) /* escape */
{
i+= Get_Bits(6);
 
val = Get_Bits(8);
if (val==0)
val = Get_Bits(8);
else if (val==128)
val = Get_Bits(8) - 256;
else if (val>128)
val -= 256;
 
if((sign = (val<0)))
val = -val;
}
else
{
i+= tab->run;
val = tab->level;
sign = Get_Bits(1);
}
 
if (i>=64)
{
if (!Quiet_Flag)
fprintf(stderr,"DCT coeff index (i) out of bounds (inter)\n");
Fault_Flag = 1;
return;
}
 
j = scan[ZIG_ZAG][i];
val = (((val<<1)+1)*ld->quantizer_scale*ld->non_intra_quantizer_matrix[j]) >> 4;
 
/* mismatch control ('oddification') */
if (val!=0) /* should always be true, but it's not guaranteed */
val = (val-1) | 1; /* equivalent to: if ((val&1)==0) val = val - 1; */
 
/* saturation */
if (!sign)
bp[j] = (val>2047) ? 2047 : val; /* positive */
else
bp[j] = (val>2048) ? -2048 : -val; /* negative */
}
}
 
 
/* decode one intra coded MPEG-2 block */
 
void Decode_MPEG2_Intra_Block(comp,dc_dct_pred)
int comp;
int dc_dct_pred[];
{
int val, i, j, sign, nc, cc, run;
unsigned int code;
DCTtab *tab;
short *bp;
int *qmat;
struct layer_data *ld1;
 
/* with data partitioning, data always goes to base layer */
ld1 = (ld->scalable_mode==SC_DP) ? &base : ld;
bp = ld1->block[comp];
 
if (base.scalable_mode==SC_DP)
if (base.priority_breakpoint<64)
ld = &enhan;
else
ld = &base;
 
cc = (comp<4) ? 0 : (comp&1)+1;
 
qmat = (comp<4 || chroma_format==CHROMA420)
? ld1->intra_quantizer_matrix
: ld1->chroma_intra_quantizer_matrix;
 
/* ISO/IEC 13818-2 section 7.2.1: decode DC coefficients */
if (cc==0)
val = (dc_dct_pred[0]+= Get_Luma_DC_dct_diff());
else if (cc==1)
val = (dc_dct_pred[1]+= Get_Chroma_DC_dct_diff());
else
val = (dc_dct_pred[2]+= Get_Chroma_DC_dct_diff());
 
if (Fault_Flag) return;
 
bp[0] = val << (3-intra_dc_precision);
 
nc=0;
 
#ifdef TRACE
if (Trace_Flag)
printf("DCT(%d)i:",comp);
#endif /* TRACE */
 
/* decode AC coefficients */
for (i=1; ; i++)
{
code = Show_Bits(16);
if (code>=16384 && !intra_vlc_format)
tab = &DCTtabnext[(code>>12)-4];
else if (code>=1024)
{
if (intra_vlc_format)
tab = &DCTtab0a[(code>>8)-4];
else
tab = &DCTtab0[(code>>8)-4];
}
else if (code>=512)
{
if (intra_vlc_format)
tab = &DCTtab1a[(code>>6)-8];
else
tab = &DCTtab1[(code>>6)-8];
}
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
printf("invalid Huffman code in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
#ifdef TRACE
if (Trace_Flag)
{
printf(" (");
Print_Bits(code,16,tab->len);
}
#endif /* TRACE */
 
if (tab->run==64) /* end_of_block */
{
#ifdef TRACE
if (Trace_Flag)
printf("): EOB\n");
#endif /* TRACE */
return;
}
 
if (tab->run==65) /* escape */
{
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(6),6,6);
}
#endif /* TRACE */
 
i+= run = Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(12),12,12);
}
#endif /* TRACE */
 
val = Get_Bits(12);
if ((val&2047)==0)
{
if (!Quiet_Flag)
printf("invalid escape in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
if((sign = (val>=2048)))
val = 4096 - val;
}
else
{
i+= run = tab->run;
val = tab->level;
sign = Get_Bits(1);
 
#ifdef TRACE
if (Trace_Flag)
printf("%d",sign);
#endif /* TRACE */
}
 
if (i>=64)
{
if (!Quiet_Flag)
fprintf(stderr,"DCT coeff index (i) out of bounds (intra2)\n");
Fault_Flag = 1;
return;
}
 
#ifdef TRACE
if (Trace_Flag)
printf("): %d/%d",run,sign ? -val : val);
#endif /* TRACE */
 
j = scan[ld1->alternate_scan][i];
val = (val * ld1->quantizer_scale * qmat[j]) >> 4;
bp[j] = sign ? -val : val;
nc++;
 
if (base.scalable_mode==SC_DP && nc==base.priority_breakpoint-63)
ld = &enhan;
}
}
 
 
/* decode one non-intra coded MPEG-2 block */
 
void Decode_MPEG2_Non_Intra_Block(comp)
int comp;
{
int val, i, j, sign, nc, run;
unsigned int code;
DCTtab *tab;
short *bp;
int *qmat;
struct layer_data *ld1;
 
/* with data partitioning, data always goes to base layer */
ld1 = (ld->scalable_mode==SC_DP) ? &base : ld;
bp = ld1->block[comp];
 
if (base.scalable_mode==SC_DP)
if (base.priority_breakpoint<64)
ld = &enhan;
else
ld = &base;
 
qmat = (comp<4 || chroma_format==CHROMA420)
? ld1->non_intra_quantizer_matrix
: ld1->chroma_non_intra_quantizer_matrix;
 
nc = 0;
 
#ifdef TRACE
if (Trace_Flag)
printf("DCT(%d)n:",comp);
#endif /* TRACE */
 
/* decode AC coefficients */
for (i=0; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
{
if (i==0)
tab = &DCTtabfirst[(code>>12)-4];
else
tab = &DCTtabnext[(code>>12)-4];
}
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
printf("invalid Huffman code in Decode_MPEG2_Non_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
#ifdef TRACE
if (Trace_Flag)
{
printf(" (");
Print_Bits(code,16,tab->len);
}
#endif /* TRACE */
 
if (tab->run==64) /* end_of_block */
{
#ifdef TRACE
if (Trace_Flag)
printf("): EOB\n");
#endif /* TRACE */
return;
}
 
if (tab->run==65) /* escape */
{
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(6),6,6);
}
#endif /* TRACE */
 
i+= run = Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(12),12,12);
}
#endif /* TRACE */
 
val = Get_Bits(12);
if ((val&2047)==0)
{
if (!Quiet_Flag)
printf("invalid escape in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
if((sign = (val>=2048)))
val = 4096 - val;
}
else
{
i+= run = tab->run;
val = tab->level;
sign = Get_Bits(1);
 
#ifdef TRACE
if (Trace_Flag)
printf("%d",sign);
#endif /* TRACE */
}
 
if (i>=64)
{
if (!Quiet_Flag)
fprintf(stderr,"DCT coeff index (i) out of bounds (inter2)\n");
Fault_Flag = 1;
return;
}
 
#ifdef TRACE
if (Trace_Flag)
printf("): %d/%d",run,sign?-val:val);
#endif /* TRACE */
 
j = scan[ld1->alternate_scan][i];
val = (((val<<1)+1) * ld1->quantizer_scale * qmat[j]) >> 5;
bp[j] = sign ? -val : val;
nc++;
 
if (base.scalable_mode==SC_DP && nc==base.priority_breakpoint-63)
ld = &enhan;
}
}
/advdemos/branches/advdemos/mpeg2/spatscal.c
0,0 → 1,331
 
#include <stdio.h>
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void Read_Lower_Layer_Component_Framewise _ANSI_ARGS_((int comp, int lw, int lh));
static void Read_Lower_Layer_Component_Fieldwise _ANSI_ARGS_((int comp, int lw, int lh));
static void Make_Spatial_Prediction_Frame _ANSI_ARGS_((int progressive_frame,
int llprogressive_frame, unsigned char *fld0, unsigned char *fld1,
short *tmp, unsigned char *dst, int llx0, int lly0, int llw, int llh,
int horizontal_size, int vertical_size, int vm, int vn, int hm, int hn,
int aperture));
static void Deinterlace _ANSI_ARGS_((unsigned char *fld0, unsigned char *fld1,
int j0, int lx, int ly, int aperture));
static void Subsample_Vertical _ANSI_ARGS_((unsigned char *s, short *d,
int lx, int lys, int lyd, int m, int n, int j0, int dj));
static void Subsample_Horizontal _ANSI_ARGS_((short *s, unsigned char *d,
int x0, int lx, int lxs, int lxd, int ly, int m, int n));
 
 
 
/* get reference frame */
void Spatial_Prediction()
{
if(Frame_Store_Flag)
{
Read_Lower_Layer_Component_Framewise(0,lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size); /* Y */
Read_Lower_Layer_Component_Framewise(1,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cb ("U") */
Read_Lower_Layer_Component_Framewise(2,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cr ("V") */
}
else
{
Read_Lower_Layer_Component_Fieldwise(0,lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size); /* Y */
Read_Lower_Layer_Component_Fieldwise(1,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cb ("U") */
Read_Lower_Layer_Component_Fieldwise(2,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cr ("V") */
}
 
 
Make_Spatial_Prediction_Frame /* Y */
(progressive_frame,lower_layer_progressive_frame,llframe0[0],llframe1[0],
lltmp,current_frame[0],lower_layer_horizontal_offset,
lower_layer_vertical_offset,
lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size,
horizontal_size,vertical_size,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,
picture_structure!=FRAME_PICTURE); /* this changed from CD to DIS */
 
Make_Spatial_Prediction_Frame /* Cb */
(progressive_frame,lower_layer_progressive_frame,llframe0[1],llframe1[1],
lltmp,current_frame[1],lower_layer_horizontal_offset/2,
lower_layer_vertical_offset/2,
lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1,
horizontal_size>>1,vertical_size>>1,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,1);
 
Make_Spatial_Prediction_Frame /* Cr */
(progressive_frame,lower_layer_progressive_frame,llframe0[2],llframe1[2],
lltmp,current_frame[2],lower_layer_horizontal_offset/2,
lower_layer_vertical_offset/2,
lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1,
horizontal_size>>1,vertical_size>>1,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,1);
 
}
 
static void Read_Lower_Layer_Component_Framewise(comp,lw,lh)
int comp;
int lw, lh;
{
FILE *fd;
char fname[256];
char ext[3][3] = {".Y",".U",".V"};
/* char *ext = {".Y",".U",".V"}; */
int i,j;
 
sprintf(fname,Lower_Layer_Picture_Filename,True_Framenum);
strcat(fname,ext[comp]);
#ifdef VERBOSE
if (Verbose_Flag>1)
printf("reading %s\n",fname);
#endif
fd=fopen(fname,"rb");
if (fd==NULL) sys_abort(-1); // PJ exit(-1);
for (j=0; j<lh; j++) {
for (i=0; i<lw; i++)
llframe0[comp][lw*j+i]=getc(fd);
if (! lower_layer_progressive_frame) {
j++;
for (i=0; i<lw; i++)
llframe1[comp][lw*j+i]=getc(fd);
}
}
fclose(fd);
}
 
 
static void Read_Lower_Layer_Component_Fieldwise(comp,lw,lh)
int comp;
int lw, lh;
{
FILE *fd;
char fname[256];
char ext[3][3] = {".Y",".U",".V"};
/* char *ext = {".Y",".U",".V"}; */
int i,j;
 
sprintf(fname,Lower_Layer_Picture_Filename,True_Framenum,lower_layer_progressive_frame ? 'f':'a');
strcat(fname,ext[comp]);
#ifdef VERBOSE
if (Verbose_Flag>1)
printf("reading %s\n",fname);
#endif
fd=fopen(fname,"rb");
if (fd==NULL) sys_abort(-1); // PJ exit(-1);
for (j=0; j<lh; j+=lower_layer_progressive_frame?1:2)
for (i=0; i<lw; i++)
llframe0[comp][lw*j+i]=getc(fd);
fclose(fd);
 
if (! lower_layer_progressive_frame) {
sprintf(fname,Lower_Layer_Picture_Filename,True_Framenum,'b');
strcat(fname,ext[comp]);
#ifdef VERBOSE
if (Verbose_Flag>1)
printf("reading %s\n",fname);
#endif
fd=fopen(fname,"rb");
if (fd==NULL) sys_abort(-1); // PJ exit(-1);
for (j=1; j<lh; j+=2)
for (i=0; i<lw; i++)
llframe1[comp][lw*j+i]=getc(fd);
fclose(fd);
}
}
 
 
/* form spatial prediction */
static void Make_Spatial_Prediction_Frame(progressive_frame,
llprogressive_frame,fld0,fld1,tmp,dst,llx0,lly0,llw,llh,horizontal_size,
vertical_size,vm,vn,hm,hn,aperture)
int progressive_frame,llprogressive_frame;
unsigned char *fld0,*fld1;
short *tmp;
unsigned char *dst;
int llx0,lly0,llw,llh,horizontal_size,vertical_size,vm,vn,hm,hn,aperture;
{
int w, h, x0, llw2, llh2;
 
llw2 = (llw*hn)/hm;
llh2 = (llh*vn)/vm;
 
if (llprogressive_frame)
{
/* progressive -> progressive / interlaced */
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,1);
}
else if (progressive_frame)
{
/* interlaced -> progressive */
if (lower_layer_deinterlaced_field_select)
{
Deinterlace(fld1,fld0,0,llw,llh,aperture);
Subsample_Vertical(fld1,tmp,llw,llh,llh2,vm,vn,0,1);
}
else
{
Deinterlace(fld0,fld1,1,llw,llh,aperture);
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,1);
}
}
else
{
/* interlaced -> interlaced */
Deinterlace(fld0,fld1,1,llw,llh,aperture);
Deinterlace(fld1,fld0,0,llw,llh,aperture);
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,2);
Subsample_Vertical(fld1,tmp,llw,llh,llh2,vm,vn,1,2);
}
 
/* vertical limits */
if (lly0<0)
{
tmp-= llw*lly0;
llh2+= lly0;
if (llh2<0)
llh2 = 0;
h = (vertical_size<llh2) ? vertical_size : llh2;
}
else
{
dst+= horizontal_size*lly0;
h= vertical_size - lly0;
if (h>llh2)
h = llh2;
}
 
/* horizontal limits */
if (llx0<0)
{
x0 = -llx0;
llw2+= llx0;
if (llw2<0)
llw2 = 0;
w = (horizontal_size<llw2) ? horizontal_size : llw2;
}
else
{
dst+= llx0;
x0 = 0;
w = horizontal_size - llx0;
if (w>llw2)
w = llw2;
}
Subsample_Horizontal(tmp,dst,x0,w,llw,horizontal_size,h,hm,hn);
}
 
/* deinterlace one field (interpolate opposite parity samples)
*
* deinterlacing is done in-place: if j0=1, fld0 contains the input field in
* its even lines and the odd lines are interpolated by this routine
* if j0=0, the input field is in the odd lines and the even lines are
* interpolated
*
* fld0: field to be deinterlaced
* fld1: other field (referenced by the two field aperture filter)
* j0: 0: interpolate even (top) lines, 1: interpolate odd (bottom) lines
* lx: width of fld0 and fld1
* ly: height of the deinterlaced field (has to be even)
* aperture: 1: use one field aperture filter (two field otherwise)
*/
static void Deinterlace(fld0,fld1,j0,lx,ly,aperture)
unsigned char *fld0,*fld1;
int j0,lx,ly; /* ly has to be even */
int aperture;
{
int i,j,v;
unsigned char *p0, *p0m1, *p0p1, *p1, *p1m2, *p1p2;
 
/* deinterlace one field */
for (j=j0; j<ly; j+=2)
{
p0 = fld0+lx*j;
p0m1 = (j==0) ? p0+lx : p0-lx;
p0p1 = (j==ly-1) ? p0-lx : p0+lx;
 
if (aperture)
for (i=0; i<lx; i++)
p0[i] = (unsigned int)(p0m1[i] + p0p1[i] + 1)>>1;
else
{
p1 = fld1 + lx*j;
p1m2 = (j<2) ? p1 : p1-2*lx;
p1p2 = (j>=ly-2) ? p1 : p1+2*lx;
for (i=0; i<lx; i++)
{
v = 8*(p0m1[i]+p0p1[i]) + 2*p1[i] - p1m2[i] - p1p2[i];
p0[i] = Clip[(v + ((v>=0) ? 8 : 7))>>4];
}
}
}
}
 
/* vertical resampling */
static void Subsample_Vertical(s,d,lx,lys,lyd,m,n,j0,dj)
unsigned char *s;
short *d;
int lx, lys, lyd, m, n, j0, dj;
{
int i, j, c1, c2, jd;
unsigned char *s1, *s2;
short *d1;
 
for (j=j0; j<lyd; j+=dj)
{
d1 = d + lx*j;
jd = (j*m)/n;
s1 = s + lx*jd;
s2 = (jd<lys-1)? s1+lx : s1;
c2 = (16*((j*m)%n) + (n>>1))/n;
c1 = 16 - c2;
for (i=0; i<lx; i++)
d1[i] = c1*s1[i] + c2*s2[i];
}
}
 
/* horizontal resampling */
static void Subsample_Horizontal(s,d,x0,lx,lxs,lxd,ly,m,n)
short *s;
unsigned char *d;
int x0, lx, lxs, lxd, ly, m, n;
{
int i, i1, j, id, c1, c2, v;
short *s1, *s2;
unsigned char *d1;
 
for (i1=0; i1<lx; i1++)
{
d1 = d + i1;
i = x0 + i1;
id = (i*m)/n;
s1 = s+id;
s2 = (id<lxs-1) ? s1+1 : s1;
c2 = (16*((i*m)%n) + (n>>1))/n;
c1 = 16 - c2;
for (j=0; j<ly; j++)
{
v = c1*(*s1) + c2*(*s2);
*d1 = (v + ((v>=0) ? 128 : 127))>>8;
d1+= lxd;
s1+= lxs;
s2+= lxs;
}
}
}
 
 
/advdemos/branches/advdemos/mpeg2/readme
0,0 → 1,72
This is the S.Ha.R.K. porting of the MPEG2 decoder from the
MPEG Software Simulation Group.
 
---------------------------------------------------------------------------
 
The original source code is available on the web at
http://www.mpeg.org
 
The demo uses the FAT16 filesystem and the graphics card.
I just added these files:
- gvideo.c Video initialization and output
- jetctrl.c Idle time visualization
- makefile S.Ha.R.K. Makefile for the demo
- store.c interface between the original decoder and S.Ha.R.K.
 
The original makefile and store.c files has also been renamed to store.ori.
 
---------------------------------------------------------------------------
 
The demo simply intercets the Write_Frame function and puts the decoded
frame into a buffer. The task created in gvideo is a periodic CBS task
that reads a picture from the buffer and simply displays it.
 
===========================================================================
 
This is the original readme file:
 
 
January 9, 1995:
=====
Pre-release caveats:
 
- has only been tested with gcc. (I'm not sure we will even bother
with acc, or cc in the future).
 
- I'm fully aware of the warnings received by -Wall
 
- Verifier still not integrated (due to complexity), although
experimental vbv_delay code included in verify.c
 
 
December 20, 1995
===============================================================
Frame buffer substitution edition of decoder.
 
Restrictions:
- temporal_reference in bitstream must be correct.
 
- substitute pictures must have pixel (luminance samples) width
and height equal to coded_picture_width (mb_width*16) and
coded_picture_height (mb_height*16) rather than horizontal_size
and vertical_size, respectively.
 
- all input pictures must be interleaved into a frame.
 
- frame count (index) is based on absolute display frame order with
no repeated (3:2 pulldown) fields or frames.
 
--------------------------------------------------------
Notes:
 
- command line arguements in this edition differ from verifier
style. This decoder's arguments are the same as the
public distribution's (July 4, 1994) code .
 
please note that this code, with frame buffer substitution, when it
is released will use the verifier style of arguments.
 
- Carsten's updated spatial scalability decoder routines have been
incorperated.
 
/advdemos/branches/advdemos/mpeg2/gvideo.c
0,0 → 1,157
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 1999 Luca Abeni and Massimiliano Giorgi
*
* This program 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.
*
* This program 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
*
*/
 
/*
* CVS : $Id: gvideo.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
*
* File: $File$
* Revision: $Revision: 1.1.1.1 $
* Last update: $Date: 2004-05-24 17:54:50 $
*/
 
//#include "config.h"
 
#include <kernel/func.h>
#include <kernel/model.h>
#include <kernel/const.h>
 
#include <drivers/glib.h>
 
#include <stdlib.h>
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
 
#include "config.h"
#include "global.h"
 
#define COLORFG rgb16(255,255,255)
#define COLORBG rgb16(0,0,0)
 
#define SP rgb16(0,128,0)
#define FG rgb16(255,255,255)
#define BG rgb16(0,0,0)
 
/* border size (pixels) */
#define BO 4
 
 
//#define NOGRX
 
/*
*
*/
 
 
void draw_frame(int x, int y, int dx, int dy)
{
#ifndef NOGRX
grx_box(x-1-BO,y-1-BO,x+dx+BO,y+dy+BO,SP);
grx_rect(x-1-BO,y-1-BO,x+dx+BO,y+dy+BO,FG);
grx_box(x,y,x+dx-1,y+dy-1,BG);
grx_rect(x-1,y-1,x+dx,y+dy,FG);
#endif
}
 
static TASK play(void *arg)
{
int x1,y1,x2,y2;
int moreframes;
struct framebuf_struct *fbuf;
x1=1;
y1=1;
x2=x1+Coded_Picture_Width-1;
y2=y1+Coded_Picture_Height-1;
moreframes=1;
task_nopreempt();
 
while (moreframes) {
fbuf = remove_frame();
#ifndef NOGRX
// grxlock();
// grx_rect(10,10,10+5*fbuf->n,10+5*fbuf->n,FG);
grx_putimage(x1, y1, x2, y2, fbuf->f);
// grxunlock();
#else
cprintf("(%d %d)\n",fbuf->n, fbuf->f);
#endif
give_back_framebuf(fbuf);
task_endcycle();
}
return NULL;
}
 
void gvideo_init(void)
{
SOFT_TASK_MODEL model;
PID pid;
int period,wcet;
 
#ifndef NOGRX
grx_init();
grx_setmode(grx_getmode(800, 600, 16));
#endif
 
// draw_frame(0, 0, CodedImageWidth,CodedImageHeight);
 
srand(7);
 
period=1000000/20;
wcet=20000;
soft_task_default_model(model);
soft_task_def_met(model,wcet);
soft_task_def_wcet(model,wcet);
soft_task_def_period(model,period);
soft_task_def_periodic(model);
soft_task_def_ctrl_jet(model);
pid=task_create("Video",play,&model,NULL);
if (pid!=-1) task_activate(pid);
}
 
 
 
 
 
 
 
 
/advdemos/branches/advdemos/mpeg2/gethdr.c
0,0 → 1,1077
/* gethdr.c, header decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
 
 
/* private prototypes */
static void sequence_header _ANSI_ARGS_((void));
static void group_of_pictures_header _ANSI_ARGS_((void));
static void picture_header _ANSI_ARGS_((void));
static void extension_and_user_data _ANSI_ARGS_((void));
static void sequence_extension _ANSI_ARGS_((void));
static void sequence_display_extension _ANSI_ARGS_((void));
static void quant_matrix_extension _ANSI_ARGS_((void));
static void sequence_scalable_extension _ANSI_ARGS_((void));
static void picture_display_extension _ANSI_ARGS_((void));
static void picture_coding_extension _ANSI_ARGS_((void));
static void picture_spatial_scalable_extension _ANSI_ARGS_((void));
static void picture_temporal_scalable_extension _ANSI_ARGS_((void));
static int extra_bit_information _ANSI_ARGS_((void));
static void copyright_extension _ANSI_ARGS_((void));
static void user_data _ANSI_ARGS_((void));
static void user_data _ANSI_ARGS_((void));
 
 
 
 
/* introduced in September 1995 to assist spatial scalable decoding */
static void Update_Temporal_Reference_Tacking_Data _ANSI_ARGS_((void));
/* private variables */
static int Temporal_Reference_Base = 0;
static int True_Framenum_max = -1;
static int Temporal_Reference_GOP_Reset = 0;
 
#define RESERVED -1
static double frame_rate_Table[16] =
{
0.0,
((23.0*1000.0)/1001.0),
24.0,
25.0,
((30.0*1000.0)/1001.0),
30.0,
50.0,
((60.0*1000.0)/1001.0),
60.0,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED
};
 
/*
* decode headers from one input stream
* until an End of Sequence or picture start code
* is found
*/
int Get_Hdr()
{
unsigned int code;
 
for (;;)
{
/* look for next_start_code */
next_start_code();
code = Get_Bits32();
switch (code)
{
case SEQUENCE_HEADER_CODE:
sequence_header();
break;
case GROUP_START_CODE:
group_of_pictures_header();
break;
case PICTURE_START_CODE:
picture_header();
return 1;
break;
case SEQUENCE_END_CODE:
return 0;
break;
default:
if (!Quiet_Flag)
fprintf(stderr,"Unexpected next_start_code %08x (ignored)\n",code);
break;
}
}
}
 
 
/* align to start of next next_start_code */
 
void next_start_code()
{
/* byte align */
Flush_Buffer(ld->Incnt&7);
while (Show_Bits(24)!=0x01L)
Flush_Buffer(8);
}
 
 
/* decode sequence header */
 
static void sequence_header()
{
int i;
int pos;
 
pos = ld->Bitcnt;
horizontal_size = Get_Bits(12);
vertical_size = Get_Bits(12);
aspect_ratio_information = Get_Bits(4);
frame_rate_code = Get_Bits(4);
bit_rate_value = Get_Bits(18);
marker_bit("sequence_header()");
vbv_buffer_size = Get_Bits(10);
constrained_parameters_flag = Get_Bits(1);
 
if((ld->load_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
else
{
for (i=0; i<64; i++)
ld->intra_quantizer_matrix[i] = default_intra_quantizer_matrix[i];
}
 
if((ld->load_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->non_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
else
{
for (i=0; i<64; i++)
ld->non_intra_quantizer_matrix[i] = 16;
}
 
/* copy luminance to chrominance matrices */
for (i=0; i<64; i++)
{
ld->chroma_intra_quantizer_matrix[i] =
ld->intra_quantizer_matrix[i];
 
ld->chroma_non_intra_quantizer_matrix[i] =
ld->non_intra_quantizer_matrix[i];
}
 
#ifdef VERBOSE
if (Verbose_Flag > NO_LAYER)
{
printf("sequence header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag > SEQUENCE_LAYER)
{
printf(" horizontal_size=%d\n",horizontal_size);
printf(" vertical_size=%d\n",vertical_size);
printf(" aspect_ratio_information=%d\n",aspect_ratio_information);
printf(" frame_rate_code=%d",frame_rate_code);
printf(" bit_rate_value=%d\n",bit_rate_value);
printf(" vbv_buffer_size=%d\n",vbv_buffer_size);
printf(" constrained_parameters_flag=%d\n",constrained_parameters_flag);
printf(" load_intra_quantizer_matrix=%d\n",ld->load_intra_quantizer_matrix);
printf(" load_non_intra_quantizer_matrix=%d\n",ld->load_non_intra_quantizer_matrix);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_header++;
#endif /* VERIFY */
 
extension_and_user_data();
}
 
 
 
/* decode group of pictures header */
/* ISO/IEC 13818-2 section 6.2.2.6 */
static void group_of_pictures_header()
{
int pos;
 
if (ld == &base)
{
Temporal_Reference_Base = True_Framenum_max + 1; /* *CH* */
Temporal_Reference_GOP_Reset = 1;
}
pos = ld->Bitcnt;
drop_flag = Get_Bits(1);
hour = Get_Bits(5);
minute = Get_Bits(6);
marker_bit("group_of_pictures_header()");
sec = Get_Bits(6);
frame = Get_Bits(6);
closed_gop = Get_Bits(1);
broken_link = Get_Bits(1);
 
#ifdef VERBOSE
if (Verbose_Flag > NO_LAYER)
{
printf("group of pictures (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag > SEQUENCE_LAYER)
{
printf(" drop_flag=%d\n",drop_flag);
printf(" timecode %d:%02d:%02d:%02d\n",hour,minute,sec,frame);
printf(" closed_gop=%d\n",closed_gop);
printf(" broken_link=%d\n",broken_link);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_group_of_pictures_header++;
#endif /* VERIFY */
 
extension_and_user_data();
 
}
 
 
/* decode picture header */
 
/* ISO/IEC 13818-2 section 6.2.3 */
static void picture_header()
{
int pos;
int Extra_Information_Byte_Count;
 
/* unless later overwritten by picture_spatial_scalable_extension() */
ld->pict_scal = 0;
pos = ld->Bitcnt;
temporal_reference = Get_Bits(10);
picture_coding_type = Get_Bits(3);
vbv_delay = Get_Bits(16);
 
if (picture_coding_type==P_TYPE || picture_coding_type==B_TYPE)
{
full_pel_forward_vector = Get_Bits(1);
forward_f_code = Get_Bits(3);
}
if (picture_coding_type==B_TYPE)
{
full_pel_backward_vector = Get_Bits(1);
backward_f_code = Get_Bits(3);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("picture header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" temporal_reference=%d\n",temporal_reference);
printf(" picture_coding_type=%d\n",picture_coding_type);
printf(" vbv_delay=%d\n",vbv_delay);
if (picture_coding_type==P_TYPE || picture_coding_type==B_TYPE)
{
printf(" full_pel_forward_vector=%d\n",full_pel_forward_vector);
printf(" forward_f_code =%d\n",forward_f_code);
}
if (picture_coding_type==B_TYPE)
{
printf(" full_pel_backward_vector=%d\n",full_pel_backward_vector);
printf(" backward_f_code =%d\n",backward_f_code);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_header++;
#endif /* VERIFY */
 
Extra_Information_Byte_Count =
extra_bit_information();
extension_and_user_data();
 
/* update tracking information used to assist spatial scalability */
Update_Temporal_Reference_Tacking_Data();
}
 
/* decode slice header */
 
/* ISO/IEC 13818-2 section 6.2.4 */
int slice_header()
{
int slice_vertical_position_extension;
int quantizer_scale_code;
int pos;
int slice_picture_id_enable = 0;
int slice_picture_id = 0;
int extra_information_slice = 0;
 
pos = ld->Bitcnt;
 
slice_vertical_position_extension =
(ld->MPEG2_Flag && vertical_size>2800) ? Get_Bits(3) : 0;
 
if (ld->scalable_mode==SC_DP)
ld->priority_breakpoint = Get_Bits(7);
 
quantizer_scale_code = Get_Bits(5);
ld->quantizer_scale =
ld->MPEG2_Flag ? (ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] : quantizer_scale_code<<1) : quantizer_scale_code;
 
/* slice_id introduced in March 1995 as part of the video corridendum
(after the IS was drafted in November 1994) */
if (Get_Bits(1))
{
ld->intra_slice = Get_Bits(1);
 
slice_picture_id_enable = Get_Bits(1);
slice_picture_id = Get_Bits(6);
 
extra_information_slice = extra_bit_information();
}
else
ld->intra_slice = 0;
 
#ifdef VERBOSE
if (Verbose_Flag>PICTURE_LAYER)
{
printf("slice header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SLICE_LAYER)
{
if (ld->MPEG2_Flag && vertical_size>2800)
printf(" slice_vertical_position_extension=%d\n",slice_vertical_position_extension);
if (ld->scalable_mode==SC_DP)
printf(" priority_breakpoint=%d\n",ld->priority_breakpoint);
 
printf(" quantizer_scale_code=%d\n",quantizer_scale_code);
 
printf(" slice_picture_id_enable = %d\n", slice_picture_id_enable);
 
if(slice_picture_id_enable)
printf(" slice_picture_id = %d\n", slice_picture_id);
 
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_slice_header++;
#endif /* VERIFY */
 
 
return slice_vertical_position_extension;
}
 
 
/* decode extension and user data */
/* ISO/IEC 13818-2 section 6.2.2.2 */
static void extension_and_user_data()
{
int code,ext_ID;
 
next_start_code();
 
while ((code = Show_Bits(32))==EXTENSION_START_CODE || code==USER_DATA_START_CODE)
{
if (code==EXTENSION_START_CODE)
{
Flush_Buffer32();
ext_ID = Get_Bits(4);
switch (ext_ID)
{
case SEQUENCE_EXTENSION_ID:
sequence_extension();
break;
case SEQUENCE_DISPLAY_EXTENSION_ID:
sequence_display_extension();
break;
case QUANT_MATRIX_EXTENSION_ID:
quant_matrix_extension();
break;
case SEQUENCE_SCALABLE_EXTENSION_ID:
sequence_scalable_extension();
break;
case PICTURE_DISPLAY_EXTENSION_ID:
picture_display_extension();
break;
case PICTURE_CODING_EXTENSION_ID:
picture_coding_extension();
break;
case PICTURE_SPATIAL_SCALABLE_EXTENSION_ID:
picture_spatial_scalable_extension();
break;
case PICTURE_TEMPORAL_SCALABLE_EXTENSION_ID:
picture_temporal_scalable_extension();
break;
case COPYRIGHT_EXTENSION_ID:
copyright_extension();
break;
default:
fprintf(stderr,"reserved extension start code ID %d\n",ext_ID);
break;
}
next_start_code();
}
else
{
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
printf("user data\n");
#endif /* VERBOSE */
Flush_Buffer32();
user_data();
}
}
}
 
 
/* decode sequence extension */
 
/* ISO/IEC 13818-2 section 6.2.2.3 */
static void sequence_extension()
{
int horizontal_size_extension;
int vertical_size_extension;
int bit_rate_extension;
int vbv_buffer_size_extension;
int pos;
 
/* derive bit position for trace */
#ifdef VERBOSE
pos = ld->Bitcnt;
#endif
 
ld->MPEG2_Flag = 1;
 
ld->scalable_mode = SC_NONE; /* unless overwritten by sequence_scalable_extension() */
layer_id = 0; /* unless overwritten by sequence_scalable_extension() */
profile_and_level_indication = Get_Bits(8);
progressive_sequence = Get_Bits(1);
chroma_format = Get_Bits(2);
horizontal_size_extension = Get_Bits(2);
vertical_size_extension = Get_Bits(2);
bit_rate_extension = Get_Bits(12);
marker_bit("sequence_extension");
vbv_buffer_size_extension = Get_Bits(8);
low_delay = Get_Bits(1);
frame_rate_extension_n = Get_Bits(2);
frame_rate_extension_d = Get_Bits(5);
 
frame_rate = frame_rate_Table[frame_rate_code] *
((frame_rate_extension_n+1)/(frame_rate_extension_d+1));
 
/* special case for 422 profile & level must be made */
if((profile_and_level_indication>>7) & 1)
{ /* escape bit of profile_and_level_indication set */
/* 4:2:2 Profile @ Main Level */
if((profile_and_level_indication&15)==5)
{
profile = PROFILE_422;
level = MAIN_LEVEL;
}
}
else
{
profile = profile_and_level_indication >> 4; /* Profile is upper nibble */
level = profile_and_level_indication & 0xF; /* Level is lower nibble */
}
horizontal_size = (horizontal_size_extension<<12) | (horizontal_size&0x0fff);
vertical_size = (vertical_size_extension<<12) | (vertical_size&0x0fff);
 
 
/* ISO/IEC 13818-2 does not define bit_rate_value to be composed of
* both the original bit_rate_value parsed in sequence_header() and
* the optional bit_rate_extension in sequence_extension_header().
* However, we use it for bitstream verification purposes.
*/
 
bit_rate_value += (bit_rate_extension << 18);
bit_rate = ((double) bit_rate_value) * 400.0;
vbv_buffer_size += (vbv_buffer_size_extension << 10);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("sequence extension (byte %d)\n",(pos>>3)-4);
 
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" profile_and_level_indication=%d\n",profile_and_level_indication);
 
if (profile_and_level_indication<128)
{
printf(" profile=%d, level=%d\n",profile,level);
}
 
printf(" progressive_sequence=%d\n",progressive_sequence);
printf(" chroma_format=%d\n",chroma_format);
printf(" horizontal_size_extension=%d\n",horizontal_size_extension);
printf(" vertical_size_extension=%d\n",vertical_size_extension);
printf(" bit_rate_extension=%d\n",bit_rate_extension);
printf(" vbv_buffer_size_extension=%d\n",vbv_buffer_size_extension);
printf(" low_delay=%d\n",low_delay);
printf(" frame_rate_extension_n=%d\n",frame_rate_extension_n);
printf(" frame_rate_extension_d=%d\n",frame_rate_extension_d);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_extension++;
#endif /* VERIFY */
 
 
}
 
 
/* decode sequence display extension */
 
static void sequence_display_extension()
{
int pos;
 
pos = ld->Bitcnt;
video_format = Get_Bits(3);
color_description = Get_Bits(1);
 
if (color_description)
{
color_primaries = Get_Bits(8);
transfer_characteristics = Get_Bits(8);
matrix_coefficients = Get_Bits(8);
}
 
display_horizontal_size = Get_Bits(14);
marker_bit("sequence_display_extension");
display_vertical_size = Get_Bits(14);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("sequence display extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
 
printf(" video_format=%d\n",video_format);
printf(" color_description=%d\n",color_description);
 
if (color_description)
{
printf(" color_primaries=%d\n",color_primaries);
printf(" transfer_characteristics=%d\n",transfer_characteristics);
printf(" matrix_coefficients=%d\n",matrix_coefficients);
}
printf(" display_horizontal_size=%d\n",display_horizontal_size);
printf(" display_vertical_size=%d\n",display_vertical_size);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_display_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode quant matrix entension */
/* ISO/IEC 13818-2 section 6.2.3.2 */
static void quant_matrix_extension()
{
int i;
int pos;
 
pos = ld->Bitcnt;
 
if((ld->load_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
{
ld->chroma_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= ld->intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= Get_Bits(8);
}
}
 
if((ld->load_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
{
ld->chroma_non_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= ld->non_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= Get_Bits(8);
}
}
 
if((ld->load_chroma_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->chroma_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
 
if((ld->load_chroma_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->chroma_non_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("quant matrix extension (byte %d)\n",(pos>>3)-4);
printf(" load_intra_quantizer_matrix=%d\n",
ld->load_intra_quantizer_matrix);
printf(" load_non_intra_quantizer_matrix=%d\n",
ld->load_non_intra_quantizer_matrix);
printf(" load_chroma_intra_quantizer_matrix=%d\n",
ld->load_chroma_intra_quantizer_matrix);
printf(" load_chroma_non_intra_quantizer_matrix=%d\n",
ld->load_chroma_non_intra_quantizer_matrix);
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_quant_matrix_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode sequence scalable extension */
/* ISO/IEC 13818-2 section 6.2.2.5 */
static void sequence_scalable_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
/* values (without the +1 offset) of scalable_mode are defined in
Table 6-10 of ISO/IEC 13818-2 */
ld->scalable_mode = Get_Bits(2) + 1; /* add 1 to make SC_DP != SC_NONE */
 
layer_id = Get_Bits(4);
 
if (ld->scalable_mode==SC_SPAT)
{
lower_layer_prediction_horizontal_size = Get_Bits(14);
marker_bit("sequence_scalable_extension()");
lower_layer_prediction_vertical_size = Get_Bits(14);
horizontal_subsampling_factor_m = Get_Bits(5);
horizontal_subsampling_factor_n = Get_Bits(5);
vertical_subsampling_factor_m = Get_Bits(5);
vertical_subsampling_factor_n = Get_Bits(5);
}
 
if (ld->scalable_mode==SC_TEMP)
Error("temporal scalability not implemented\n");
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("sequence scalable extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" scalable_mode=%d\n",ld->scalable_mode-1);
printf(" layer_id=%d\n",layer_id);
if (ld->scalable_mode==SC_SPAT)
{
printf(" lower_layer_prediction_horiontal_size=%d\n",
lower_layer_prediction_horizontal_size);
printf(" lower_layer_prediction_vertical_size=%d\n",
lower_layer_prediction_vertical_size);
printf(" horizontal_subsampling_factor_m=%d\n",
horizontal_subsampling_factor_m);
printf(" horizontal_subsampling_factor_n=%d\n",
horizontal_subsampling_factor_n);
printf(" vertical_subsampling_factor_m=%d\n",
vertical_subsampling_factor_m);
printf(" vertical_subsampling_factor_n=%d\n",
vertical_subsampling_factor_n);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_scalable_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture display extension */
/* ISO/IEC 13818-2 section 6.2.3.3. */
static void picture_display_extension()
{
int i;
int number_of_frame_center_offsets;
int pos;
 
pos = ld->Bitcnt;
/* based on ISO/IEC 13818-2 section 6.3.12
(November 1994) Picture display extensions */
 
/* derive number_of_frame_center_offsets */
if(progressive_sequence)
{
if(repeat_first_field)
{
if(top_field_first)
number_of_frame_center_offsets = 3;
else
number_of_frame_center_offsets = 2;
}
else
{
number_of_frame_center_offsets = 1;
}
}
else
{
if(picture_structure!=FRAME_PICTURE)
{
number_of_frame_center_offsets = 1;
}
else
{
if(repeat_first_field)
number_of_frame_center_offsets = 3;
else
number_of_frame_center_offsets = 2;
}
}
 
 
/* now parse */
for (i=0; i<number_of_frame_center_offsets; i++)
{
frame_center_horizontal_offset[i] = Get_Bits(16);
marker_bit("picture_display_extension, first marker bit");
frame_center_vertical_offset[i] = Get_Bits(16);
marker_bit("picture_display_extension, second marker bit");
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("picture display extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
 
for (i=0; i<number_of_frame_center_offsets; i++)
{
printf(" frame_center_horizontal_offset[%d]=%d\n",i,
frame_center_horizontal_offset[i]);
printf(" frame_center_vertical_offset[%d]=%d\n",i,
frame_center_vertical_offset[i]);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_display_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture coding extension */
static void picture_coding_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
f_code[0][0] = Get_Bits(4);
f_code[0][1] = Get_Bits(4);
f_code[1][0] = Get_Bits(4);
f_code[1][1] = Get_Bits(4);
 
intra_dc_precision = Get_Bits(2);
picture_structure = Get_Bits(2);
top_field_first = Get_Bits(1);
frame_pred_frame_dct = Get_Bits(1);
concealment_motion_vectors = Get_Bits(1);
ld->q_scale_type = Get_Bits(1);
intra_vlc_format = Get_Bits(1);
ld->alternate_scan = Get_Bits(1);
repeat_first_field = Get_Bits(1);
chroma_420_type = Get_Bits(1);
progressive_frame = Get_Bits(1);
composite_display_flag = Get_Bits(1);
 
if (composite_display_flag)
{
v_axis = Get_Bits(1);
field_sequence = Get_Bits(3);
sub_carrier = Get_Bits(1);
burst_amplitude = Get_Bits(7);
sub_carrier_phase = Get_Bits(8);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("picture coding extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" forward horizontal f_code=%d\n", f_code[0][0]);
printf(" forward vertical f_code=%d\n", f_code[0][1]);
printf(" backward horizontal f_code=%d\n", f_code[1][0]);
printf(" backward_vertical f_code=%d\n", f_code[1][1]);
printf(" intra_dc_precision=%d\n",intra_dc_precision);
printf(" picture_structure=%d\n",picture_structure);
printf(" top_field_first=%d\n",top_field_first);
printf(" frame_pred_frame_dct=%d\n",frame_pred_frame_dct);
printf(" concealment_motion_vectors=%d\n",concealment_motion_vectors);
printf(" q_scale_type=%d\n",ld->q_scale_type);
printf(" intra_vlc_format=%d\n",intra_vlc_format);
printf(" alternate_scan=%d\n",ld->alternate_scan);
printf(" repeat_first_field=%d\n",repeat_first_field);
printf(" chroma_420_type=%d\n",chroma_420_type);
printf(" progressive_frame=%d\n",progressive_frame);
printf(" composite_display_flag=%d\n",composite_display_flag);
 
if (composite_display_flag)
{
printf(" v_axis=%d\n",v_axis);
printf(" field_sequence=%d\n",field_sequence);
printf(" sub_carrier=%d\n",sub_carrier);
printf(" burst_amplitude=%d\n",burst_amplitude);
printf(" sub_carrier_phase=%d\n",sub_carrier_phase);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_coding_extension++;
#endif /* VERIFY */
}
 
 
/* decode picture spatial scalable extension */
/* ISO/IEC 13818-2 section 6.2.3.5. */
static void picture_spatial_scalable_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
ld->pict_scal = 1; /* use spatial scalability in this picture */
 
lower_layer_temporal_reference = Get_Bits(10);
marker_bit("picture_spatial_scalable_extension(), first marker bit");
lower_layer_horizontal_offset = Get_Bits(15);
if (lower_layer_horizontal_offset>=16384)
lower_layer_horizontal_offset-= 32768;
marker_bit("picture_spatial_scalable_extension(), second marker bit");
lower_layer_vertical_offset = Get_Bits(15);
if (lower_layer_vertical_offset>=16384)
lower_layer_vertical_offset-= 32768;
spatial_temporal_weight_code_table_index = Get_Bits(2);
lower_layer_progressive_frame = Get_Bits(1);
lower_layer_deinterlaced_field_select = Get_Bits(1);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
printf("picture spatial scalable extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" lower_layer_temporal_reference=%d\n",lower_layer_temporal_reference);
printf(" lower_layer_horizontal_offset=%d\n",lower_layer_horizontal_offset);
printf(" lower_layer_vertical_offset=%d\n",lower_layer_vertical_offset);
printf(" spatial_temporal_weight_code_table_index=%d\n",
spatial_temporal_weight_code_table_index);
printf(" lower_layer_progressive_frame=%d\n",lower_layer_progressive_frame);
printf(" lower_layer_deinterlaced_field_select=%d\n",lower_layer_deinterlaced_field_select);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_spatial_scalable_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture temporal scalable extension
*
* not implemented
*/
/* ISO/IEC 13818-2 section 6.2.3.4. */
static void picture_temporal_scalable_extension()
{
Error("temporal scalability not supported\n");
 
#ifdef VERIFY
verify_picture_temporal_scalable_extension++;
#endif /* VERIFY */
}
 
 
/* decode extra bit information */
/* ISO/IEC 13818-2 section 6.2.3.4. */
static int extra_bit_information()
{
int Byte_Count = 0;
 
while (Get_Bits1())
{
Flush_Buffer(8);
Byte_Count++;
}
 
return(Byte_Count);
}
 
 
 
/* ISO/IEC 13818-2 section 5.3 */
/* Purpose: this function is mainly designed to aid in bitstream conformance
testing. A simple Flush_Buffer(1) would do */
void marker_bit(text)
char *text;
{
int marker;
 
marker = Get_Bits(1);
 
#ifdef VERIFY
if(!marker)
printf("ERROR: %s--marker_bit set to 0",text);
#endif
}
 
 
/* ISO/IEC 13818-2 sections 6.3.4.1 and 6.2.2.2.2 */
static void user_data()
{
/* skip ahead to the next start code */
next_start_code();
}
 
 
 
/* Copyright extension */
/* ISO/IEC 13818-2 section 6.2.3.6. */
/* (header added in November, 1994 to the IS document) */
 
 
static void copyright_extension()
{
int pos;
int reserved_data;
 
pos = ld->Bitcnt;
 
copyright_flag = Get_Bits(1);
copyright_identifier = Get_Bits(8);
original_or_copy = Get_Bits(1);
/* reserved */
reserved_data = Get_Bits(7);
 
marker_bit("copyright_extension(), first marker bit");
copyright_number_1 = Get_Bits(20);
marker_bit("copyright_extension(), second marker bit");
copyright_number_2 = Get_Bits(22);
marker_bit("copyright_extension(), third marker bit");
copyright_number_3 = Get_Bits(22);
 
if(Verbose_Flag>NO_LAYER)
{
printf("copyright_extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
printf(" copyright_flag =%d\n",copyright_flag);
printf(" copyright_identifier=%d\n",copyright_identifier);
printf(" original_or_copy = %d (original=1, copy=0)\n",
original_or_copy);
printf(" copyright_number_1=%d\n",copyright_number_1);
printf(" copyright_number_2=%d\n",copyright_number_2);
printf(" copyright_number_3=%d\n",copyright_number_3);
}
}
 
#ifdef VERIFY
verify_copyright_extension++;
#endif /* VERIFY */
}
 
 
 
/* introduced in September 1995 to assist Spatial Scalability */
static void Update_Temporal_Reference_Tacking_Data()
{
static int temporal_reference_wrap = 0;
static int temporal_reference_old = 0;
 
if (ld == &base) /* *CH* */
{
if (picture_coding_type!=B_TYPE && temporal_reference!=temporal_reference_old)
/* check first field of */
{
/* non-B-frame */
if (temporal_reference_wrap)
{/* wrap occured at previous I- or P-frame */
/* now all intervening B-frames which could
still have high temporal_reference values are done */
Temporal_Reference_Base += 1024;
temporal_reference_wrap = 0;
}
/* distinguish from a reset */
if (temporal_reference<temporal_reference_old && !Temporal_Reference_GOP_Reset)
temporal_reference_wrap = 1; /* we must have just passed a GOP-Header! */
temporal_reference_old = temporal_reference;
Temporal_Reference_GOP_Reset = 0;
}
 
True_Framenum = Temporal_Reference_Base + temporal_reference;
/* temporary wrap of TR at 1024 for M frames */
if (temporal_reference_wrap && temporal_reference <= temporal_reference_old)
True_Framenum += 1024;
 
True_Framenum_max = (True_Framenum > True_Framenum_max) ?
True_Framenum : True_Framenum_max;
}
}
/advdemos/branches/advdemos/mpeg2/m.bat
0,0 → 1,0
x mpeg2dec -b /shark/mpeg2/m.m2v
/advdemos/branches/advdemos/mpeg2/idct.c
0,0 → 1,211
/* idct.c, inverse fast discrete cosine transform */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/**********************************************************/
/* inverse two dimensional DCT, Chen-Wang algorithm */
/* (cf. IEEE ASSP-32, pp. 803-816, Aug. 1984) */
/* 32-bit integer arithmetic (8 bit coefficients) */
/* 11 mults, 29 adds per DCT */
/* sE, 18.8.91 */
/**********************************************************/
/* coefficients extended to 12 bit for IEEE1180-1990 */
/* compliance sE, 2.1.94 */
/**********************************************************/
 
/* this code assumes >> to be a two's-complement arithmetic */
/* right shift: (-2)>>1 == -1 , (-3)>>1 == -2 */
 
#include "config.h"
 
#define W1 2841 /* 2048*sqrt(2)*cos(1*pi/16) */
#define W2 2676 /* 2048*sqrt(2)*cos(2*pi/16) */
#define W3 2408 /* 2048*sqrt(2)*cos(3*pi/16) */
#define W5 1609 /* 2048*sqrt(2)*cos(5*pi/16) */
#define W6 1108 /* 2048*sqrt(2)*cos(6*pi/16) */
#define W7 565 /* 2048*sqrt(2)*cos(7*pi/16) */
 
/* global declarations */
void Initialize_Fast_IDCT _ANSI_ARGS_((void));
void Fast_IDCT _ANSI_ARGS_((short *block));
 
/* private data */
static short iclip[1024]; /* clipping table */
static short *iclp;
 
/* private prototypes */
static void idctrow _ANSI_ARGS_((short *blk));
static void idctcol _ANSI_ARGS_((short *blk));
 
/* row (horizontal) IDCT
*
* 7 pi 1
* dst[k] = sum c[l] * src[l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 128
* c[1..7] = 128*sqrt(2)
*/
 
static void idctrow(blk)
short *blk;
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
 
/* shortcut */
if (!((x1 = blk[4]<<11) | (x2 = blk[6]) | (x3 = blk[2]) |
(x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3])))
{
blk[0]=blk[1]=blk[2]=blk[3]=blk[4]=blk[5]=blk[6]=blk[7]=blk[0]<<3;
return;
}
 
x0 = (blk[0]<<11) + 128; /* for proper rounding in the fourth stage */
 
/* first stage */
x8 = W7*(x4+x5);
x4 = x8 + (W1-W7)*x4;
x5 = x8 - (W1+W7)*x5;
x8 = W3*(x6+x7);
x6 = x8 - (W3-W5)*x6;
x7 = x8 - (W3+W5)*x7;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2);
x2 = x1 - (W2+W6)*x2;
x3 = x1 + (W2-W6)*x3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[0] = (x7+x1)>>8;
blk[1] = (x3+x2)>>8;
blk[2] = (x0+x4)>>8;
blk[3] = (x8+x6)>>8;
blk[4] = (x8-x6)>>8;
blk[5] = (x0-x4)>>8;
blk[6] = (x3-x2)>>8;
blk[7] = (x7-x1)>>8;
}
 
/* column (vertical) IDCT
*
* 7 pi 1
* dst[8*k] = sum c[l] * src[8*l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 1/1024
* c[1..7] = (1/1024)*sqrt(2)
*/
static void idctcol(blk)
short *blk;
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
 
/* shortcut */
if (!((x1 = (blk[8*4]<<8)) | (x2 = blk[8*6]) | (x3 = blk[8*2]) |
(x4 = blk[8*1]) | (x5 = blk[8*7]) | (x6 = blk[8*5]) | (x7 = blk[8*3])))
{
blk[8*0]=blk[8*1]=blk[8*2]=blk[8*3]=blk[8*4]=blk[8*5]=blk[8*6]=blk[8*7]=
iclp[(blk[8*0]+32)>>6];
return;
}
 
x0 = (blk[8*0]<<8) + 8192;
 
/* first stage */
x8 = W7*(x4+x5) + 4;
x4 = (x8+(W1-W7)*x4)>>3;
x5 = (x8-(W1+W7)*x5)>>3;
x8 = W3*(x6+x7) + 4;
x6 = (x8-(W3-W5)*x6)>>3;
x7 = (x8-(W3+W5)*x7)>>3;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2) + 4;
x2 = (x1-(W2+W6)*x2)>>3;
x3 = (x1+(W2-W6)*x3)>>3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[8*0] = iclp[(x7+x1)>>14];
blk[8*1] = iclp[(x3+x2)>>14];
blk[8*2] = iclp[(x0+x4)>>14];
blk[8*3] = iclp[(x8+x6)>>14];
blk[8*4] = iclp[(x8-x6)>>14];
blk[8*5] = iclp[(x0-x4)>>14];
blk[8*6] = iclp[(x3-x2)>>14];
blk[8*7] = iclp[(x7-x1)>>14];
}
 
/* two dimensional inverse discrete cosine transform */
void Fast_IDCT(block)
short *block;
{
int i;
 
for (i=0; i<8; i++)
idctrow(block+8*i);
 
for (i=0; i<8; i++)
idctcol(block+i);
}
 
void Initialize_Fast_IDCT()
{
int i;
 
iclp = iclip+512;
for (i= -512; i<512; i++)
iclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i);
}
/advdemos/branches/advdemos/mpeg2/makefile.ori
0,0 → 1,98
# Makefile for mpeg2decode
 
# Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved.
 
#
# Disclaimer of Warranty
#
# These software programs are available to the user without any license fee or
# royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
# any and all warranties, whether express, implied, or statuary, including any
# implied warranties or merchantability or of fitness for a particular
# purpose. In no event shall the copyright-holder be liable for any
# incidental, punitive, or consequential damages of any kind whatsoever
# arising from the use of these programs.
#
# This disclaimer of warranty extends to the user of these programs and user's
# customers, employees, agents, transferees, successors, and assigns.
#
# The MPEG Software Simulation Group does not represent or warrant that the
# programs furnished hereunder are free of infringement of any third-party
# patents.
#
# Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
# are subject to royalty fees to patent holders. Many of these patents are
# general enough such that they are unavoidable regardless of implementation
# design.
#
#
 
#WARNINGS = -Wall
#VERIFY = -DVERIFY
 
#disable this flag if you do not want bitstream element tracing
#this will speed up the decoder some since it does not have to test
#the trace flag at several critical inner loop locations.
TRACE = -DTRACE
 
#disable this flag if you do not need verbose trace, such as
#header information
VERBOSE = -DVERBOSE
 
# uncomment the following two lines if you want to include X11 support
 
#USE_DISP = -DDISPLAY
#LIBS = -lX11
 
# uncomment the following two lines if you want to use shared memory
# (faster display if server and client run on the same machine)
 
#USE_SHMEM = -DSH_MEM
#LIBS = -lXext -lX11
 
# if your X11 include files / libraries are in a non standard location:
# set INCLUDEDIR to -I followed by the appropriate include file path and
# set LIBRARYDIR to -L followed by the appropriate library path and
 
#INCLUDEDIR = -I/usr/openwin/include
#LIBRARYDIR = -L/usr/openwin/lib
 
#
# GNU gcc
#
CC = gcc
CFLAGS = -O2 $(USE_DISP) $(USE_SHMEM) $(INCLUDEDIR) $(TRACE) $(VERBOSE) $(VERIFY) $(WARNINGS)
 
OBJ = mpeg2dec.o getpic.o motion.o getvlc.o gethdr.o getblk.o getbits.o store.o recon.o spatscal.o idct.o idctref.o display.o systems.o subspic.o verify.o
 
all: mpeg2decode
 
pc: mpeg2dec.exe
 
clean:
rm -f *.o *% core mpeg2decode
 
mpeg2dec.exe: mpeg2decode
coff2exe mpeg2dec
 
mpeg2decode: $(OBJ)
$(CC) $(CFLAGS) $(LIBRARYDIR) -o mpeg2decode $(OBJ) -lm $(LIBS)
 
display.o : display.c config.h global.h mpeg2dec.h
getbits.o : getbits.c config.h global.h mpeg2dec.h
getblk.o : getblk.c config.h global.h mpeg2dec.h
gethdr.o : gethdr.c config.h global.h mpeg2dec.h
getpic.o : getpic.c config.h global.h mpeg2dec.h
getvlc.o : getvlc.c config.h global.h mpeg2dec.h getvlc.h
idct.o : idct.c config.h
idctref.o : idctref.c config.h
motion.o : motion.c config.h global.h mpeg2dec.h
mpeg2dec.o : mpeg2dec.c config.h global.h mpeg2dec.h
recon.o : recon.c config.h global.h mpeg2dec.h
spatscal.o : spatscal.c config.h global.h mpeg2dec.h
store.o : store.c config.h global.h mpeg2dec.h
 
# additions since July 4, 1994 edition
systems.o : systems.c config.h global.h mpeg2dec.h
subspic.o : subspic.c config.h global.h mpeg2dec.h
verify.o: verify.c config.h global.h mpeg2dec.h
/advdemos/branches/advdemos/mpeg2/getvlc.c
0,0 → 1,799
/* getvlc.c, variable length decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
 
#include "config.h"
#include "global.h"
#include "getvlc.h"
 
/* private prototypes */
/* generic picture macroblock type processing functions */
static int Get_I_macroblock_type _ANSI_ARGS_((void));
static int Get_P_macroblock_type _ANSI_ARGS_((void));
static int Get_B_macroblock_type _ANSI_ARGS_((void));
static int Get_D_macroblock_type _ANSI_ARGS_((void));
 
/* spatial picture macroblock type processing functions */
static int Get_I_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_P_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_B_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_SNR_macroblock_type _ANSI_ARGS_((void));
 
int Get_macroblock_type()
{
int macroblock_type = 0;
 
if (ld->scalable_mode==SC_SNR)
macroblock_type = Get_SNR_macroblock_type();
else
{
switch (picture_coding_type)
{
case I_TYPE:
macroblock_type = ld->pict_scal ? Get_I_Spatial_macroblock_type() : Get_I_macroblock_type();
break;
case P_TYPE:
macroblock_type = ld->pict_scal ? Get_P_Spatial_macroblock_type() : Get_P_macroblock_type();
break;
case B_TYPE:
macroblock_type = ld->pict_scal ? Get_B_Spatial_macroblock_type() : Get_B_macroblock_type();
break;
case D_TYPE:
macroblock_type = Get_D_macroblock_type();
break;
default:
printf("Get_macroblock_type(): unrecognized picture coding type\n");
break;
}
}
 
return macroblock_type;
}
 
static int Get_I_macroblock_type()
{
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(I) ");
#endif /* TRACE */
 
if (Get_Bits1())
{
#ifdef TRACE
if (Trace_Flag)
printf("(1): Intra (1)\n");
#endif /* TRACE */
return 1;
}
 
if (!Get_Bits1())
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
}
 
#ifdef TRACE
if (Trace_Flag)
printf("(01): Intra, Quant (17)\n");
#endif /* TRACE */
 
return 17;
}
 
static char *MBdescr[]={
"", "Intra", "No MC, Coded", "",
"Bwd, Not Coded", "", "Bwd, Coded", "",
"Fwd, Not Coded", "", "Fwd, Coded", "",
"Interp, Not Coded", "", "Interp, Coded", "",
"", "Intra, Quant", "No MC, Coded, Quant", "",
"", "", "Bwd, Coded, Quant", "",
"", "", "Fwd, Coded, Quant", "",
"", "", "Interp, Coded, Quant", ""
};
 
static int Get_P_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(P) (");
#endif /* TRACE */
 
if ((code = Show_Bits(6))>=8)
{
code >>= 3;
Flush_Buffer(PMBtab0[code].len);
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,3,PMBtab0[code].len);
printf("): %s (%d)\n",MBdescr[(int)PMBtab0[code].val],PMBtab0[code].val);
}
#endif /* TRACE */
return PMBtab0[code].val;
}
 
if (code==0)
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(PMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,PMBtab1[code].len);
printf("): %s (%d)\n",MBdescr[(int)PMBtab1[code].val],PMBtab1[code].val);
}
#endif /* TRACE */
 
return PMBtab1[code].val;
}
 
static int Get_B_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(B) (");
#endif /* TRACE */
 
if ((code = Show_Bits(6))>=8)
{
code >>= 2;
Flush_Buffer(BMBtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,BMBtab0[code].len);
printf("): %s (%d)\n",MBdescr[(int)BMBtab0[code].val],BMBtab0[code].val);
}
#endif /* TRACE */
 
return BMBtab0[code].val;
}
 
if (code==0)
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(BMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,BMBtab1[code].len);
printf("): %s (%d)\n",MBdescr[(int)BMBtab1[code].val],BMBtab1[code].val);
}
#endif /* TRACE */
 
return BMBtab1[code].val;
}
 
static int Get_D_macroblock_type()
{
if (!Get_Bits1())
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag=1;
}
 
return 1;
}
 
/* macroblock_type for pictures with spatial scalability */
static int Get_I_Spatial_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(I,spat) (");
#endif /* TRACE */
 
code = Show_Bits(4);
 
if (code==0)
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,spIMBtab[code].len);
printf("): %02x\n",spIMBtab[code].val);
}
#endif /* TRACE */
 
Flush_Buffer(spIMBtab[code].len);
return spIMBtab[code].val;
}
 
static int Get_P_Spatial_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(P,spat) (");
#endif /* TRACE */
 
code = Show_Bits(7);
 
if (code<2)
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
if (code>=16)
{
code >>= 3;
Flush_Buffer(spPMBtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,spPMBtab0[code].len);
printf("): %02x\n",spPMBtab0[code].val);
}
#endif /* TRACE */
 
return spPMBtab0[code].val;
}
 
Flush_Buffer(spPMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,7,spPMBtab1[code].len);
printf("): %02x\n",spPMBtab1[code].val);
}
#endif /* TRACE */
 
return spPMBtab1[code].val;
}
 
static int Get_B_Spatial_macroblock_type()
{
int code;
VLCtab *p;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_type(B,spat) (");
#endif /* TRACE */
 
code = Show_Bits(9);
 
if (code>=64)
p = &spBMBtab0[(code>>5)-2];
else if (code>=16)
p = &spBMBtab1[(code>>2)-4];
else if (code>=8)
p = &spBMBtab2[code-8];
else
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(p->len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,9,p->len);
printf("): %02x\n",p->val);
}
#endif /* TRACE */
 
return p->val;
}
 
static int Get_SNR_macroblock_type()
{
int code;
 
#ifdef TRACE /* *CH* */
if (Trace_Flag)
printf("macroblock_type(SNR) (");
#endif
 
code = Show_Bits(3);
 
if (code==0)
{
if (!Quiet_Flag)
printf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(SNRMBtab[code].len);
 
#ifdef TRACE /* *CH* */
if (Trace_Flag)
{
Print_Bits(code,3,SNRMBtab[code].len);
printf("): %s (%d)\n",MBdescr[(int)SNRMBtab[code].val],SNRMBtab[code].val);
}
#endif
 
 
return SNRMBtab[code].val;
}
 
int Get_motion_code()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("motion_code (");
#endif /* TRACE */
 
if (Get_Bits1())
{
#ifdef TRACE
if (Trace_Flag)
printf("0): 0\n");
#endif /* TRACE */
return 0;
}
 
if ((code = Show_Bits(9))>=64)
{
code >>= 6;
Flush_Buffer(MVtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,3,MVtab0[code].len);
printf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab0[code].val:MVtab0[code].val);
}
#endif /* TRACE */
 
return Get_Bits1()?-MVtab0[code].val:MVtab0[code].val;
}
 
if (code>=24)
{
code >>= 3;
Flush_Buffer(MVtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,MVtab1[code].len);
printf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab1[code].val:MVtab1[code].val);
}
#endif /* TRACE */
 
return Get_Bits1()?-MVtab1[code].val:MVtab1[code].val;
}
 
if ((code-=12)<0)
{
if (!Quiet_Flag)
/* HACK */
printf("Invalid motion_vector code (MBA %d, pic %d)\n", global_MBA, global_pic);
Fault_Flag=1;
return 0;
}
 
Flush_Buffer(MVtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code+12,9,MVtab2[code].len);
printf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab2[code].val:MVtab2[code].val);
}
#endif /* TRACE */
 
return Get_Bits1() ? -MVtab2[code].val : MVtab2[code].val;
}
 
/* get differential motion vector (for dual prime prediction) */
int Get_dmvector()
{
#ifdef TRACE
if (Trace_Flag)
printf("dmvector (");
#endif /* TRACE */
 
if (Get_Bits(1))
{
#ifdef TRACE
if (Trace_Flag)
printf(Show_Bits(1) ? "11): -1\n" : "10): 1\n");
#endif /* TRACE */
return Get_Bits(1) ? -1 : 1;
}
else
{
#ifdef TRACE
if (Trace_Flag)
printf("0): 0\n");
#endif /* TRACE */
return 0;
}
}
 
int Get_coded_block_pattern()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
printf("coded_block_pattern_420 (");
#endif /* TRACE */
 
if ((code = Show_Bits(9))>=128)
{
code >>= 4;
Flush_Buffer(CBPtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,5,CBPtab0[code].len);
printf("): ");
Print_Bits(CBPtab0[code].val,6,6);
printf(" (%d)\n",CBPtab0[code].val);
}
#endif /* TRACE */
 
return CBPtab0[code].val;
}
 
if (code>=8)
{
code >>= 1;
Flush_Buffer(CBPtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,8,CBPtab1[code].len);
printf("): ");
Print_Bits(CBPtab1[code].val,6,6);
printf(" (%d)\n",CBPtab1[code].val);
}
#endif /* TRACE */
 
return CBPtab1[code].val;
}
 
if (code<1)
{
if (!Quiet_Flag)
printf("Invalid coded_block_pattern code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(CBPtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,9,CBPtab2[code].len);
printf("): ");
Print_Bits(CBPtab2[code].val,6,6);
printf(" (%d)\n",CBPtab2[code].val);
}
#endif /* TRACE */
 
return CBPtab2[code].val;
}
 
int Get_macroblock_address_increment()
{
int code, val;
 
#ifdef TRACE
if (Trace_Flag)
printf("macroblock_address_increment (");
#endif /* TRACE */
 
val = 0;
 
while ((code = Show_Bits(11))<24)
{
if (code!=15) /* if not macroblock_stuffing */
{
if (code==8) /* if macroblock_escape */
{
#ifdef TRACE
if (Trace_Flag)
printf("00000001000 ");
#endif /* TRACE */
 
val+= 33;
}
else
{
if (!Quiet_Flag)
printf("Invalid macroblock_address_increment code\n");
 
Fault_Flag = 1;
return 1;
}
}
else /* macroblock suffing */
{
#ifdef TRACE
if (Trace_Flag)
printf("00000001111 ");
#endif /* TRACE */
}
 
Flush_Buffer(11);
}
 
/* macroblock_address_increment == 1 */
/* ('1' is in the MSB position of the lookahead) */
if (code>=1024)
{
Flush_Buffer(1);
#ifdef TRACE
if (Trace_Flag)
printf("1): %d\n",val+1);
#endif /* TRACE */
return val + 1;
}
 
/* codes 00010 ... 011xx */
if (code>=128)
{
/* remove leading zeros */
code >>= 6;
Flush_Buffer(MBAtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,5,MBAtab1[code].len);
printf("): %d\n",val+MBAtab1[code].val);
}
#endif /* TRACE */
 
return val + MBAtab1[code].val;
}
/* codes 00000011000 ... 0000111xxxx */
code-= 24; /* remove common base */
Flush_Buffer(MBAtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code+24,11,MBAtab2[code].len);
printf("): %d\n",val+MBAtab2[code].val);
}
#endif /* TRACE */
 
return val + MBAtab2[code].val;
}
 
/* combined MPEG-1 and MPEG-2 stage. parse VLC and
perform dct_diff arithmetic.
 
MPEG-1: ISO/IEC 11172-2 section
MPEG-2: ISO/IEC 13818-2 section 7.2.1
Note: the arithmetic here is presented more elegantly than
the spec, yet the results, dct_diff, are the same.
*/
 
int Get_Luma_DC_dct_diff()
{
int code, size, dct_diff;
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("dct_dc_size_luminance: (");
*/
#endif /* TRACE */
 
/* decode length */
code = Show_Bits(5);
 
if (code<31)
{
size = DClumtab0[code].val;
Flush_Buffer(DClumtab0[code].len);
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code,5,DClumtab0[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
else
{
code = Show_Bits(9) - 0x1f0;
size = DClumtab1[code].val;
Flush_Buffer(DClumtab1[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code+0x1f0,9,DClumtab1[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf(", dct_dc_differential (");
*/
#endif /* TRACE */
 
if (size==0)
dct_diff = 0;
else
{
dct_diff = Get_Bits(size);
#ifdef TRACE
/*
if (Trace_Flag)
Print_Bits(dct_diff,size,size);
*/
#endif /* TRACE */
if ((dct_diff & (1<<(size-1)))==0)
dct_diff-= (1<<size) - 1;
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("): %d\n",dct_diff);
*/
#endif /* TRACE */
 
return dct_diff;
}
 
 
int Get_Chroma_DC_dct_diff()
{
int code, size, dct_diff;
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("dct_dc_size_chrominance: (");
*/
#endif /* TRACE */
 
/* decode length */
code = Show_Bits(5);
 
if (code<31)
{
size = DCchromtab0[code].val;
Flush_Buffer(DCchromtab0[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code,5,DCchromtab0[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
else
{
code = Show_Bits(10) - 0x3e0;
size = DCchromtab1[code].val;
Flush_Buffer(DCchromtab1[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code+0x3e0,10,DCchromtab1[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf(", dct_dc_differential (");
*/
#endif /* TRACE */
 
if (size==0)
dct_diff = 0;
else
{
dct_diff = Get_Bits(size);
#ifdef TRACE
/*
if (Trace_Flag)
Print_Bits(dct_diff,size,size);
*/
#endif /* TRACE */
if ((dct_diff & (1<<(size-1)))==0)
dct_diff-= (1<<size) - 1;
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("): %d\n",dct_diff);
*/
#endif /* TRACE */
 
return dct_diff;
}
/advdemos/branches/advdemos/mpeg2/todo
0,0 → 1,73
1. Test bitstream
Small example bitstream (128x128 pixel dimensions) which employs all
picture_structure (top field, bottom field, frame), picture_coding_type
(I, P, and B), macroblock_type (forwards/backwards/interpolated,
intra/non-intra, coded/not-coded, quant/no quant, etc.), and
motion_type (field, frame, 16X8, dual prime) modes.
 
2. add trace printing for mpeg1 getblk routines.
 
3. modify getsys.c to parse program layer bitstreams (Systems)
with variable-length packets.
 
4. 24 bit X11 display
(borrow from Berkeley or find way for our code to use their interface)
 
5. MPEG-2 Transport layer systems streams parsing
 
6. Document IPR issue
 
provide CableLabs URL
how IPR relates to our disclaimer.
 
7. TIFF library support (YCbCr 4:4:4, 4:2:2, and 4:2:0 pictures)
[deferred]
10. IDCT rounding
As per IDCT corridgendum (Savatier, MPEG 95/XXX)
[done, but verified ?]
 
 
12. green dots in can
[ appears to be a display issue, probably related to convmat[]
error ]
 
19. move Dual_Prime calculation into picture_data()
 
20. motion vector calculation to include tappable stages to test
whether elements fall within [low:high] range.
 
21. Integrate verifier routines
 
22. Inter-layer verification routines
- check base and enhancement layers (e.g. SNR)
 
23. Spatial verification
- considering that no base layer is available.
 
24. SNR verification
[ done ]
 
25. DP verification
[ not done. No longer any bitstreams with Data Partitioning distributed
since DP is not part of any official Profile ]
 
26. merge all global bitsteam element variables into
common data structure (similar to layer_data). This is needed
for the verifier (whether or not headers in SNR and DP streams
are identical where needed to that of the base layer).
 
27. investigate why MS-DOS wants an extra % sign for filename patterns
when more than one filename pattern is used in the command line argument
 
28. convert -t (trace) flag into levels, merge with Verbose.
 
29. seek to a specified frame number (support for MCI-like functions)
 
30. document the "flash" VLC table decoding method in detail.
(namely how to map tables in Annex B to those in getvlc.h)
 
31. MPEG-2 program stream compatibility
(a few minor bits of difference in the system header ).
 
--------
/advdemos/branches/advdemos/mpeg2/mpeg2dec.c
0,0 → 1,770
 
/* mpeg2dec.c, main(), initialization, option processing */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
 
#define GLOBAL
#include "config.h"
#include "global.h"
 
/* private prototypes */
static int video_sequence _ANSI_ARGS_((int *framenum));
static int Decode_Bitstream _ANSI_ARGS_((void));
static int Headers _ANSI_ARGS_((void));
static void Initialize_Sequence _ANSI_ARGS_((void));
static void Initialize_Decoder _ANSI_ARGS_((void));
static void Deinitialize_Sequence _ANSI_ARGS_((void));
static void Process_Options _ANSI_ARGS_((int argc, char *argv[]));
 
 
#if OLD
static int Get_Val _ANSI_ARGS_((char *argv[]));
#endif
 
/* #define DEBUG */
 
static void Clear_Options();
#ifdef DEBUG
static void Print_Options();
#endif
 
int main(argc,argv)
int argc;
char *argv[];
{
int ret, code;
 
Clear_Options();
 
/* decode command line arguments */
Process_Options(argc,argv);
 
#ifdef DEBUG
Print_Options();
#endif
 
ld = &base; /* select base layer context */
 
/* open MPEG base layer bitstream file(s) */
/* NOTE: this is either a base layer stream or a spatial enhancement stream */
if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0)
{
fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
exit(1);
}
 
 
if(base.Infile != 0)
{
Initialize_Buffer();
if(Show_Bits(8)==0x47)
{
sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
Error(Error_Text);
}
 
next_start_code();
code = Show_Bits(32);
 
switch(code)
{
case SEQUENCE_HEADER_CODE:
break;
case PACK_START_CODE:
System_Stream_Flag = 1;
case VIDEO_ELEMENTARY_STREAM:
System_Stream_Flag = 1;
break;
default:
sprintf(Error_Text,"Unable to recognize stream type\n");
Error(Error_Text);
break;
}
 
lseek(base.Infile, 0l, 0);
Initialize_Buffer();
}
 
if(base.Infile!=0)
{
lseek(base.Infile, 0l, 0);
}
 
Initialize_Buffer();
 
if(Two_Streams)
{
ld = &enhan; /* select enhancement layer context */
 
if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)
{
sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
Enhancement_Layer_Bitstream_Filename);
 
Error(Error_Text);
}
 
Initialize_Buffer();
ld = &base;
}
 
Initialize_Decoder();
 
ret = Decode_Bitstream();
 
close(base.Infile);
 
if (Two_Streams)
close(enhan.Infile);
 
return 0;
}
 
/* IMPLEMENTAION specific rouintes */
static void Initialize_Decoder()
{
int i;
 
/* Clip table */
if (!(Clip=(unsigned char *)malloc(1024)))
Error("Clip[] malloc failed\n");
 
Clip += 384;
 
for (i=-384; i<640; i++)
Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
 
/* IDCT */
if (Reference_IDCT_Flag)
Initialize_Reference_IDCT();
else
Initialize_Fast_IDCT();
 
}
 
/* mostly IMPLEMENTAION specific rouintes */
static void Initialize_Sequence()
{
int cc, size;
static int Table_6_20[3] = {6,8,12};
 
/* check scalability mode of enhancement layer */
if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
Error("unsupported scalability mode\n");
 
/* force MPEG-1 parameters for proper decoder behavior */
/* see ISO/IEC 13818-2 section D.9.14 */
if (!base.MPEG2_Flag)
{
progressive_sequence = 1;
progressive_frame = 1;
picture_structure = FRAME_PICTURE;
frame_pred_frame_dct = 1;
chroma_format = CHROMA420;
matrix_coefficients = 5;
}
 
/* round to nearest multiple of coded macroblocks */
/* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
mb_width = (horizontal_size+15)/16;
mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
: (vertical_size+15)/16;
 
Coded_Picture_Width = 16*mb_width;
Coded_Picture_Height = 16*mb_height;
 
/* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
: Coded_Picture_Width>>1;
Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
: Coded_Picture_Height>>1;
/* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
block_count = Table_6_20[chroma_format-1];
 
for (cc=0; cc<3; cc++)
{
if (cc==0)
size = Coded_Picture_Width*Coded_Picture_Height;
else
size = Chroma_Width*Chroma_Height;
 
if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
Error("backward_reference_frame[] malloc failed\n");
 
if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
Error("forward_reference_frame[] malloc failed\n");
 
if (!(auxframe[cc] = (unsigned char *)malloc(size)))
Error("auxframe[] malloc failed\n");
 
if(Ersatz_Flag)
if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
Error("substitute_frame[] malloc failed\n");
 
 
if (base.scalable_mode==SC_SPAT)
{
/* this assumes lower layer is 4:2:0 */
if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
Error("llframe0 malloc failed\n");
if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
Error("llframe1 malloc failed\n");
}
}
 
/* SCALABILITY: Spatial */
if (base.scalable_mode==SC_SPAT)
{
if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
Error("lltmp malloc failed\n");
}
 
// PJ
Initialize_framebuf( Coded_Picture_Width*Coded_Picture_Height*sizeof(WORD) );
gvideo_init();
init_jetcontrol();
#ifdef DISPLAY
if (Output_Type==T_X11)
{
Initialize_Display_Process("");
Initialize_Dither_Matrix();
}
#endif /* DISPLAY */
 
}
 
void Error(text)
char *text;
{
fprintf(stderr,text);
exit(1);
}
 
/* Trace_Flag output */
void Print_Bits(code,bits,len)
int code,bits,len;
{
int i;
for (i=0; i<len; i++)
printf("%d",(code>>(bits-1-i))&1);
}
 
 
 
/* option processing */
static void Process_Options(argc,argv)
int argc; /* argument count */
char *argv[]; /* argument vector */
{
int i, LastArg, NextArg;
 
/* at least one argument should be present */
if (argc<2)
{
printf("\n%s, %s\n",Version,Author);
printf("Usage: mpeg2decode {options}\n\
Options: -b file main bitstream (base or spatial enhancement layer)\n\
-cn file conformance report (n: level)\n\
-e file enhancement layer bitstream (SNR or Data Partitioning)\n\
-f store/display interlaced video in frame format\n\
-g concatenated file format for substitution method (-x)\n\
-in file information & statistics report (n: level)\n\
-l file file name pattern for lower layer sequence\n\
(for spatial scalability)\n\
-on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n\
-q disable warnings to stderr\n\
-r use double precision reference IDCT\n\
-t enable low level tracing to stdout\n\
-u file print user_data to stdio or file\n\
-vn verbose output (n: level)\n\
-x file filename pattern of picture substitution sequence\n\n\
File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n\
or rec%%d%%c for fieldwise storage\n\
Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n\
Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n\
\n");
exit(0);
}
 
 
Output_Type = -1;
i = 1;
 
/* command-line options are proceeded by '-' */
 
while(i < argc)
{
/* check if this is the last argument */
LastArg = ((argc-i)==1);
 
/* parse ahead to see if another flag immediately follows current
argument (this is used to tell if a filename is missing) */
if(!LastArg)
NextArg = (argv[i+1][0]=='-');
else
NextArg = 0;
 
/* second character, [1], after '-' is the switch */
if(argv[i][0]=='-')
{
switch(toupper(argv[i][1]))
{
/* third character. [2], is the value */
case 'B':
Main_Bitstream_Flag = 1;
 
if(NextArg || LastArg)
{
printf("ERROR: -b must be followed the main bitstream filename\n");
}
else
Main_Bitstream_Filename = argv[++i];
 
break;
 
 
case 'C':
 
#ifdef VERIFY
Verify_Flag = atoi(&argv[i][2]);
 
if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
{
printf("ERROR: -c level (%d) out of range [%d,%d]\n",
Verify_Flag, NO_LAYER, ALL_LAYERS);
exit(ERROR);
}
#else /* VERIFY */
printf("This program not compiled for Verify_Flag option\n");
#endif /* VERIFY */
break;
 
case 'E':
Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
if(NextArg || LastArg)
{
printf("ERROR: -e must be followed by filename\n");
exit(ERROR);
}
else
Enhancement_Layer_Bitstream_Filename = argv[++i];
 
break;
 
 
case 'F':
Frame_Store_Flag = 1;
break;
 
case 'G':
Big_Picture_Flag = 1;
break;
 
 
case 'I':
#ifdef VERIFY
Stats_Flag = atoi(&argv[i][2]);
#else /* VERIFY */
printf("WARNING: This program not compiled for -i option\n");
#endif /* VERIFY */
break;
case 'L': /* spatial scalability flag */
Spatial_Flag = 1;
 
if(NextArg || LastArg)
{
printf("ERROR: -l must be followed by filename\n");
exit(ERROR);
}
else
Lower_Layer_Picture_Filename = argv[++i];
 
break;
 
case 'O':
Output_Type = atoi(&argv[i][2]);
if((Output_Type==4) || (Output_Type==5))
Output_Picture_Filename = ""; /* no need of filename */
else if(NextArg || LastArg)
{
printf("ERROR: -o must be followed by filename\n");
exit(ERROR);
}
else
/* filename is separated by space, so it becomes the next argument */
Output_Picture_Filename = argv[++i];
 
#ifdef DISPLAY
if (Output_Type==T_X11HIQ)
{
hiQdither = 1;
Output_Type=T_X11;
}
#endif /* DISPLAY */
break;
 
case 'Q':
Quiet_Flag = 1;
break;
 
case 'R':
Reference_IDCT_Flag = 1;
break;
case 'T':
#ifdef TRACE
Trace_Flag = 1;
#else /* TRACE */
printf("WARNING: This program not compiled for -t option\n");
#endif /* TRACE */
break;
 
case 'U':
User_Data_Flag = 1;
 
case 'V':
#ifdef VERBOSE
Verbose_Flag = atoi(&argv[i][2]);
#else /* VERBOSE */
printf("This program not compiled for -v option\n");
#endif /* VERBOSE */
break;
 
 
case 'X':
Ersatz_Flag = 1;
 
if(NextArg || LastArg)
{
printf("ERROR: -x must be followed by filename\n");
exit(ERROR);
}
else
Substitute_Picture_Filename = argv[++i];
 
break;
 
 
 
default:
fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
argv[i][1]);
 
exit(ERROR);
} /* switch() */
} /* if argv[i][0] == '-' */
i++;
 
/* check for bitstream filename argument (there must always be one, at the very end
of the command line arguments */
 
} /* while() */
 
 
/* options sense checking */
 
if(Main_Bitstream_Flag!=1)
{
printf("There must be a main bitstream specified (-b filename)\n");
}
 
/* force display process to show frame pictures */
if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
Display_Progressive_Flag = 1;
else
Display_Progressive_Flag = 0;
 
#ifdef VERIFY
/* parse the bitstream, do not actually decode it completely */
 
#if 0
if(Output_Type==-1)
{
Decode_Layer = Verify_Flag;
printf("FYI: Decoding bitstream elements up to: %s\n",
Layer_Table[Decode_Layer]);
}
else
#endif
Decode_Layer = ALL_LAYERS;
 
#endif /* VERIFY */
 
/* no output type specified */
if(Output_Type==-1)
{
Output_Type = 9;
Output_Picture_Filename = "";
}
 
 
#ifdef DISPLAY
if (Output_Type==T_X11)
{
if(Frame_Store_Flag)
Display_Progressive_Flag = 1;
else
Display_Progressive_Flag = 0;
 
Frame_Store_Flag = 1; /* to avoid calling dither() twice */
}
#endif
 
 
}
 
 
#ifdef OLD
/*
this is an old routine used to convert command line arguments
into integers
*/
static int Get_Val(argv)
char *argv[];
{
int val;
 
if (sscanf(argv[1]+2,"%d",&val)!=1)
return 0;
 
while (isdigit(argv[1][2]))
argv[1]++;
 
return val;
}
#endif
 
 
 
static int Headers()
{
int ret;
 
ld = &base;
 
/* return when end of sequence (0) or picture
header has been parsed (1) */
 
ret = Get_Hdr();
 
 
if (Two_Streams)
{
ld = &enhan;
if (Get_Hdr()!=ret && !Quiet_Flag)
fprintf(stderr,"streams out of sync\n");
ld = &base;
}
 
return ret;
}
 
 
 
static int Decode_Bitstream()
{
int ret;
int Bitstream_Framenum;
 
Bitstream_Framenum = 0;
 
for(;;)
{
 
#ifdef VERIFY
Clear_Verify_Headers();
#endif /* VERIFY */
 
ret = Headers();
if(ret==1)
{
ret = video_sequence(&Bitstream_Framenum);
}
else
return(ret);
}
 
}
 
 
static void Deinitialize_Sequence()
{
int i;
 
/* clear flags */
base.MPEG2_Flag=0;
 
for(i=0;i<3;i++)
{
free(backward_reference_frame[i]);
free(forward_reference_frame[i]);
free(auxframe[i]);
 
if (base.scalable_mode==SC_SPAT)
{
free(llframe0[i]);
free(llframe1[i]);
}
}
 
if (base.scalable_mode==SC_SPAT)
free(lltmp);
 
#ifdef DISPLAY
if (Output_Type==T_X11)
Terminate_Display_Process();
#endif
}
 
 
static int video_sequence(Bitstream_Framenumber)
int *Bitstream_Framenumber;
{
int Bitstream_Framenum;
int Sequence_Framenum;
int Return_Value;
 
Bitstream_Framenum = *Bitstream_Framenumber;
Sequence_Framenum=0;
 
Initialize_Sequence();
 
/* decode picture whose header has already been parsed in
Decode_Bitstream() */
 
 
Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
 
/* update picture numbers */
if (!Second_Field)
{
Bitstream_Framenum++;
Sequence_Framenum++;
}
 
/* loop through the rest of the pictures in the sequence */
while ((Return_Value=Headers()))
{
Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
 
if (!Second_Field)
{
Bitstream_Framenum++;
Sequence_Framenum++;
}
}
 
/* put last frame */
if (Sequence_Framenum!=0)
{
Output_Last_Frame_of_Sequence(Bitstream_Framenum);
}
 
Deinitialize_Sequence();
 
#ifdef VERIFY
Clear_Verify_Headers();
#endif /* VERIFY */
 
*Bitstream_Framenumber = Bitstream_Framenum;
return(Return_Value);
}
 
 
 
static void Clear_Options()
{
Verbose_Flag = 0;
Output_Type = 0;
Output_Picture_Filename = " ";
hiQdither = 0;
Output_Type = 0;
Frame_Store_Flag = 0;
Spatial_Flag = 0;
Lower_Layer_Picture_Filename = " ";
Reference_IDCT_Flag = 0;
Trace_Flag = 0;
Quiet_Flag = 0;
Ersatz_Flag = 0;
Substitute_Picture_Filename = " ";
Two_Streams = 0;
Enhancement_Layer_Bitstream_Filename = " ";
Big_Picture_Flag = 0;
Main_Bitstream_Flag = 0;
Main_Bitstream_Filename = " ";
Verify_Flag = 0;
Stats_Flag = 0;
User_Data_Flag = 0;
}
 
 
#ifdef DEBUG
static void Print_Options()
{
printf("Verbose_Flag = %d\n", Verbose_Flag);
printf("Output_Type = %d\n", Output_Type);
printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
printf("hiQdither = %d\n", hiQdither);
printf("Output_Type = %d\n", Output_Type);
printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
printf("Spatial_Flag = %d\n", Spatial_Flag);
printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
printf("Trace_Flag = %d\n", Trace_Flag);
printf("Quiet_Flag = %d\n", Quiet_Flag);
printf("Ersatz_Flag = %d\n", Ersatz_Flag);
printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
printf("Two_Streams = %d\n", Two_Streams);
printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
printf("Verify_Flag = %d\n", Verify_Flag);
printf("Stats_Flag = %d\n", Stats_Flag);
printf("User_Data_Flag = %d\n", User_Data_Flag);
 
}
#endif
/advdemos/branches/advdemos/mpeg2/changes
0,0 → 1,95
CHANGES
----------
 
January 9, 1996 to July 17, 1996
- cleaned up some code which gave warnings.
- altered some code to be compatible with Sun CC compiler.
However, support in the makefile for non-ansi C compilers
has been dropped (this is a stupid thing to support).
 
December 20, 1995 to January 9, 1996:
 
verified on HHI #22, TCEH #23 bitstreams.
 
1. new arguments format. Got to be so many argument fields that
a new more consistent format was devised.
 
2. Frame_Store_Flag (-f) option now controls lower layer prediciton
picture format (field or framewise)
 
3. getpic() structural changes
 
 
Since December 18, 1995:
 
1. added special case for current B pictures subsframe.c which
loads entire reference frame for buffer substitution.
 
2. fixed -l omission (-lXext) in Makefile that drives Tristan nuts everytime.
 
 
Since December 14, 1995:
 
1. organized frame buffer substitution routines into subspic.c
2. added "big file" -b mode for Tristan ;-)
 
 
Since July 4, 1994:
 
1. Concatenated elementary sequences within same bitstream
 
Decode can now handle concatenated elementary video sequences of
arbitrary parameters.
2. TRACE and VERBOSE #ifdef flags
 
3. More disciplined naming convention
 
normative variables and bitstream elements defined in 13818 are
verbatim, lower case. Implementation specific routines and variables
are capitolized.
 
4. Spatial scalability corrections
- see Carsten's document (spatscal.doc)
 
5. D-pictures (picture_coding_type==D_TYPE)
 
Only two small changes were necessary to accomodate D-pictures:
 
a. in Decode_MPEG1_Intra_Block() added line which termines
subroutine after DC coefficient has been processed.
 
b. in picture_data(), added line which parses marker bit.
 
 
6. forced decoder to display frame progressively (regardless of whether
the picture is frame structured or field structured) when -f flag
is invoked in the command line arguements.
 
also: progressive_frame now decides whether a frame is to be displayed
as a frame picture to two field pictures, rather than the older convention
of testing progressive_sequence.
 
7. Adapted systems parser from Stefan's mpeg2play to mpeg2decode.
The major changes are:
 
mpeg2dec.c:
- fseek() called twice
 
gethdr.c, getpic.c:
instances of Flush_Bits(par,32) changed to Flush_Bits32(par)
 
gethdr.c
Get_Bits(par,32) changed to Get_32_Bits(par)
 
global.h
added rdmax, sysstream, and bfr[] to parameters struct.
 
8. Restructuring of getpic.c:
 
a. moved picture pointer rotation into Update_Picture_Buffers()
b. moved picture output logic into Output_Current_Frame() to
in anticipation of 3:2 pulldown
 
 
 
/advdemos/branches/advdemos/mpeg2/getvlc.h
0,0 → 1,491
/* getvlc.h, variable length code tables */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* NOTE: #define constants such as MACROBLOCK_QUANT are upper case
as per C programming convention. However, the MPEG document
(ISO/IEC 13818-2) lists them in all lower case (e.g. Annex B) */
 
/* NOTE: the VLC tables are in a flash format---a transformation
of the tables in Annex B to a form more convenient towards
parallel (more than one-bit-at-a-time) decoding */
 
typedef struct {
char val, len;
} VLCtab;
 
typedef struct {
char run, level, len;
} DCTtab;
 
/* Table B-3, macroblock_type in P-pictures, codes 001..1xx */
static VLCtab PMBtab0[8] = {
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,3},
{MACROBLOCK_PATTERN,2}, {MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1}
};
 
/* Table B-3, macroblock_type in P-pictures, codes 000001..00011x */
static VLCtab PMBtab1[8] = {
{ERROR,0},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,6},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,5}, {MACROBLOCK_QUANT|MACROBLOCK_PATTERN,5},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,5}, {MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_INTRA,5}, {MACROBLOCK_INTRA,5}
};
 
/* Table B-4, macroblock_type in B-pictures, codes 0010..11xx */
static VLCtab BMBtab0[16] = {
{ERROR,0},
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,4},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-4, macroblock_type in B-pictures, codes 000001..00011x */
static VLCtab BMBtab1[8] = {
{ERROR,0},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_INTRA,5},
{MACROBLOCK_INTRA,5}
};
 
/* Table B-5, macroblock_type in spat. scal. I-pictures, codes 0001..1xxx */
static VLCtab spIMBtab[16] = {
{ERROR,0},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,4},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,4},
{MACROBLOCK_INTRA,4},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}
};
 
/* Table B-6, macroblock_type in spat. scal. P-pictures, codes 0010..11xx */
static VLCtab spPMBtab0[16] =
{
{ERROR,0},
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,4},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3}, {MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3}, {SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-6, macroblock_type in spat. scal. P-pictures, codes 0000010..000111x */
static VLCtab spPMBtab1[16] = {
{ERROR,0},
{ERROR,0},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,7},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,7},
{MACROBLOCK_PATTERN,7},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,7},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,7},
{MACROBLOCK_INTRA,7},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_PATTERN,6}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 0010..11xx */
static VLCtab spBMBtab0[14] = {
{MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,4},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 0000100..000111x */
static VLCtab spBMBtab1[12] = {
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,7},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,7},
{MACROBLOCK_INTRA,7},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,7},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 00000100x..000001111 */
static VLCtab spBMBtab2[8] = {
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,8},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,9}
};
 
/* Table B-8, macroblock_type in spat. scal. B-pictures, codes 001..1xx */
static VLCtab SNRMBtab[8] = {
{ERROR,0},
{0,3},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1}
};
 
/* Table B-10, motion_code, codes 0001 ... 01xx */
static VLCtab MVtab0[8] =
{ {ERROR,0}, {3,3}, {2,2}, {2,2}, {1,1}, {1,1}, {1,1}, {1,1}
};
 
/* Table B-10, motion_code, codes 0000011 ... 000011x */
static VLCtab MVtab1[8] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {7,6}, {6,6}, {5,6}, {4,5}, {4,5}
};
 
/* Table B-10, motion_code, codes 0000001100 ... 000001011x */
static VLCtab MVtab2[12] =
{ {16,9}, {15,9}, {14,9}, {13,9},
{12,9}, {11,9}, {10,8}, {10,8},
{9,8}, {9,8}, {8,8}, {8,8}
};
 
/* Table B-9, coded_block_pattern, codes 01000 ... 111xx */
static VLCtab CBPtab0[32] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{62,5}, {2,5}, {61,5}, {1,5}, {56,5}, {52,5}, {44,5}, {28,5},
{40,5}, {20,5}, {48,5}, {12,5}, {32,4}, {32,4}, {16,4}, {16,4},
{8,4}, {8,4}, {4,4}, {4,4}, {60,3}, {60,3}, {60,3}, {60,3}
};
 
/* Table B-9, coded_block_pattern, codes 00000100 ... 001111xx */
static VLCtab CBPtab1[64] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{58,8}, {54,8}, {46,8}, {30,8},
{57,8}, {53,8}, {45,8}, {29,8}, {38,8}, {26,8}, {37,8}, {25,8},
{43,8}, {23,8}, {51,8}, {15,8}, {42,8}, {22,8}, {50,8}, {14,8},
{41,8}, {21,8}, {49,8}, {13,8}, {35,8}, {19,8}, {11,8}, {7,8},
{34,7}, {34,7}, {18,7}, {18,7}, {10,7}, {10,7}, {6,7}, {6,7},
{33,7}, {33,7}, {17,7}, {17,7}, {9,7}, {9,7}, {5,7}, {5,7},
{63,6}, {63,6}, {63,6}, {63,6}, {3,6}, {3,6}, {3,6}, {3,6},
{36,6}, {36,6}, {36,6}, {36,6}, {24,6}, {24,6}, {24,6}, {24,6}
};
 
/* Table B-9, coded_block_pattern, codes 000000001 ... 000000111 */
static VLCtab CBPtab2[8] =
{ {ERROR,0}, {0,9}, {39,9}, {27,9}, {59,9}, {55,9}, {47,9}, {31,9}
};
 
/* Table B-1, macroblock_address_increment, codes 00010 ... 011xx */
static VLCtab MBAtab1[16] =
{ {ERROR,0}, {ERROR,0}, {7,5}, {6,5}, {5,4}, {5,4}, {4,4}, {4,4},
{3,3}, {3,3}, {3,3}, {3,3}, {2,3}, {2,3}, {2,3}, {2,3}
};
 
/* Table B-1, macroblock_address_increment, codes 00000011000 ... 0000111xxxx */
static VLCtab MBAtab2[104] =
{
{33,11}, {32,11}, {31,11}, {30,11}, {29,11}, {28,11}, {27,11}, {26,11},
{25,11}, {24,11}, {23,11}, {22,11}, {21,10}, {21,10}, {20,10}, {20,10},
{19,10}, {19,10}, {18,10}, {18,10}, {17,10}, {17,10}, {16,10}, {16,10},
{15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8},
{14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8},
{13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8},
{12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8},
{11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8},
{10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8},
{9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7},
{9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7},
{8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7},
{8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}
};
 
/* Table B-12, dct_dc_size_luminance, codes 00xxx ... 11110 */
static VLCtab DClumtab0[32] =
{ {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2},
{2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2},
{0, 3}, {0, 3}, {0, 3}, {0, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3},
{4, 3}, {4, 3}, {4, 3}, {4, 3}, {5, 4}, {5, 4}, {6, 5}, {ERROR, 0}
};
 
/* Table B-12, dct_dc_size_luminance, codes 111110xxx ... 111111111 */
static VLCtab DClumtab1[16] =
{ {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6},
{8, 7}, {8, 7}, {8, 7}, {8, 7}, {9, 8}, {9, 8}, {10,9}, {11,9}
};
 
/* Table B-13, dct_dc_size_chrominance, codes 00xxx ... 11110 */
static VLCtab DCchromtab0[32] =
{ {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2},
{1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2},
{2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2},
{3, 3}, {3, 3}, {3, 3}, {3, 3}, {4, 4}, {4, 4}, {5, 5}, {ERROR, 0}
};
 
/* Table B-13, dct_dc_size_chrominance, codes 111110xxxx ... 1111111111 */
static VLCtab DCchromtab1[32] =
{ {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6},
{6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6},
{7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7},
{8, 8}, {8, 8}, {8, 8}, {8, 8}, {9, 9}, {9, 9}, {10,10}, {11,10}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0100 ... 1xxx (used for first (DC) coefficient)
*/
DCTtab DCTtabfirst[12] =
{
{0,2,4}, {2,1,4}, {1,1,3}, {1,1,3},
{0,1,1}, {0,1,1}, {0,1,1}, {0,1,1},
{0,1,1}, {0,1,1}, {0,1,1}, {0,1,1}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0100 ... 1xxx (used for all other coefficients)
*/
DCTtab DCTtabnext[12] =
{
{0,2,4}, {2,1,4}, {1,1,3}, {1,1,3},
{64,0,2}, {64,0,2}, {64,0,2}, {64,0,2}, /* EOB */
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 000001xx ... 00111xxx
*/
DCTtab DCTtab0[60] =
{
{65,0,6}, {65,0,6}, {65,0,6}, {65,0,6}, /* Escape */
{2,2,7}, {2,2,7}, {9,1,7}, {9,1,7},
{0,4,7}, {0,4,7}, {8,1,7}, {8,1,7},
{7,1,6}, {7,1,6}, {7,1,6}, {7,1,6},
{6,1,6}, {6,1,6}, {6,1,6}, {6,1,6},
{1,2,6}, {1,2,6}, {1,2,6}, {1,2,6},
{5,1,6}, {5,1,6}, {5,1,6}, {5,1,6},
{13,1,8}, {0,6,8}, {12,1,8}, {11,1,8},
{3,2,8}, {1,3,8}, {0,5,8}, {10,1,8},
{0,3,5}, {0,3,5}, {0,3,5}, {0,3,5},
{0,3,5}, {0,3,5}, {0,3,5}, {0,3,5},
{4,1,5}, {4,1,5}, {4,1,5}, {4,1,5},
{4,1,5}, {4,1,5}, {4,1,5}, {4,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5}
};
 
/* Table B-15, DCT coefficients table one,
* codes 000001xx ... 11111111
*/
DCTtab DCTtab0a[252] =
{
{65,0,6}, {65,0,6}, {65,0,6}, {65,0,6}, /* Escape */
{7,1,7}, {7,1,7}, {8,1,7}, {8,1,7},
{6,1,7}, {6,1,7}, {2,2,7}, {2,2,7},
{0,7,6}, {0,7,6}, {0,7,6}, {0,7,6},
{0,6,6}, {0,6,6}, {0,6,6}, {0,6,6},
{4,1,6}, {4,1,6}, {4,1,6}, {4,1,6},
{5,1,6}, {5,1,6}, {5,1,6}, {5,1,6},
{1,5,8}, {11,1,8}, {0,11,8}, {0,10,8},
{13,1,8}, {12,1,8}, {3,2,8}, {1,4,8},
{2,1,5}, {2,1,5}, {2,1,5}, {2,1,5},
{2,1,5}, {2,1,5}, {2,1,5}, {2,1,5},
{1,2,5}, {1,2,5}, {1,2,5}, {1,2,5},
{1,2,5}, {1,2,5}, {1,2,5}, {1,2,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4}, /* EOB */
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,4,5}, {0,4,5}, {0,4,5}, {0,4,5},
{0,4,5}, {0,4,5}, {0,4,5}, {0,4,5},
{0,5,5}, {0,5,5}, {0,5,5}, {0,5,5},
{0,5,5}, {0,5,5}, {0,5,5}, {0,5,5},
{9,1,7}, {9,1,7}, {1,3,7}, {1,3,7},
{10,1,7}, {10,1,7}, {0,8,7}, {0,8,7},
{0,9,7}, {0,9,7}, {0,12,8}, {0,13,8},
{2,3,8}, {4,2,8}, {0,14,8}, {0,15,8}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0000001000 ... 0000001111
*/
DCTtab DCTtab1[8] =
{
{16,1,10}, {5,2,10}, {0,7,10}, {2,3,10},
{1,4,10}, {15,1,10}, {14,1,10}, {4,2,10}
};
 
/* Table B-15, DCT coefficients table one,
* codes 000000100x ... 000000111x
*/
DCTtab DCTtab1a[8] =
{
{5,2,9}, {5,2,9}, {14,1,9}, {14,1,9},
{2,4,10}, {16,1,10}, {15,1,9}, {15,1,9}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 000000010000 ... 000000011111
*/
DCTtab DCTtab2[16] =
{
{0,11,12}, {8,2,12}, {4,3,12}, {0,10,12},
{2,4,12}, {7,2,12}, {21,1,12}, {20,1,12},
{0,9,12}, {19,1,12}, {18,1,12}, {1,5,12},
{3,3,12}, {0,8,12}, {6,2,12}, {17,1,12}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 0000000010000 ... 0000000011111
*/
DCTtab DCTtab3[16] =
{
{10,2,13}, {9,2,13}, {5,3,13}, {3,4,13},
{2,5,13}, {1,7,13}, {1,6,13}, {0,15,13},
{0,14,13}, {0,13,13}, {0,12,13}, {26,1,13},
{25,1,13}, {24,1,13}, {23,1,13}, {22,1,13}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 00000000010000 ... 00000000011111
*/
DCTtab DCTtab4[16] =
{
{0,31,14}, {0,30,14}, {0,29,14}, {0,28,14},
{0,27,14}, {0,26,14}, {0,25,14}, {0,24,14},
{0,23,14}, {0,22,14}, {0,21,14}, {0,20,14},
{0,19,14}, {0,18,14}, {0,17,14}, {0,16,14}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 000000000010000 ... 000000000011111
*/
DCTtab DCTtab5[16] =
{
{0,40,15}, {0,39,15}, {0,38,15}, {0,37,15},
{0,36,15}, {0,35,15}, {0,34,15}, {0,33,15},
{0,32,15}, {1,14,15}, {1,13,15}, {1,12,15},
{1,11,15}, {1,10,15}, {1,9,15}, {1,8,15}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 0000000000010000 ... 0000000000011111
*/
DCTtab DCTtab6[16] =
{
{1,18,16}, {1,17,16}, {1,16,16}, {1,15,16},
{6,3,16}, {16,2,16}, {15,2,16}, {14,2,16},
{13,2,16}, {12,2,16}, {11,2,16}, {31,1,16},
{30,1,16}, {29,1,16}, {28,1,16}, {27,1,16}
};
 
/advdemos/branches/advdemos/mpeg2/const.h
0,0 → 1,141
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
 
/**
------------
CVS : $Id: const.h,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
**/
 
/*
* Copyright (C) 2000 Marco Dallera and Marco Fiocca
*
* This program 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.
*
* This program 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
*
*/
 
/*
* AUTO
*
* Another Unuseful Track simulatOr
*
* Authors: Marco Dallera
* Marco Fiocca
*
*/
 
/* ------------------ */
/* Useful constants */
/* ------------------ */
 
#ifndef __CONST_H_
 
#define __CONST_H_
 
/* Screen dimensions */
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BIT_COLORS 8
 
/* Visible area */
#define TEL_WIDTH 50
#define TEL_HEIGHT 50
 
/* Car dimensions */
#define CAR_WIDTH 12
#define CAR_HEIGHT 12
#define CAR_W 8
#define CAR_H 10
 
/* Track dimensions */
#define TRACK_WIDTH 500
#define TRACK_HEIGHT 500
 
/* Track position */
#define TRACK_X1 0
#define TRACK_Y1 0
#define TRACK_X2 TRACK_X1+TRACK_WIDTH-1
#define TRACK_Y2 TRACK_Y1+TRACK_HEIGHT-1
 
/* Max number of car on track */
#define MAX_CAR_NUMBER 10
#define DRIVERS_NUMBER 20
#define MAX_DRIVER_NAME_LENGTH 20
#define MAX_TRACK_NAME_LENGTH 20
#define TRACK_NUMBER 4
 
/* Lap direction */
#define CLOCK 0
#define ANTICLOCK 1
 
/* Information display coords */
#define CMD_WIDTH TRACK_WIDTH
#define CMD_HEIGHT (SCREEN_HEIGHT-TRACK_HEIGHT-3)
 
/* Car position limits */
#define MIN_CAR_X (TRACK_X1 + CAR_WIDTH/2 + 4)
#define MIN_CAR_Y (TRACK_Y1 + CAR_HEIGHT/2 + 4)
#define MAX_CAR_X (TRACK_X2 - CAR_WIDTH/2 - 4)
#define MAX_CAR_Y (TRACK_Y2 - CAR_HEIGHT/2 - 4)
 
/* Road constants */
#define LEFT_ONLY 10
#define RIGHT_ONLY 11
#define ROAD_OK 12
#define NO_ROAD 13
 
/* Collision constants */
#define COLLISION_LEFT 20
#define COLLISION_RIGHT 21
#define COLLISION_BACK 22
#define NO_COLL 0
 
/* CAB constants */
#define ROAD_MSG_DIM sizeof(road_info)
#define ROAD_MSG_READER 4
 
#define CAR_MSG_DIM sizeof(car_status)
#define CAR_MSG_READER 5
 
/* Tasks parameters */
#define SENSOR_WCET 3000
#define SENSOR_PERIOD 40000
#define CONTROL_WCET 1000
#define CONTROL_PERIOD 40000
 
#endif
 
/advdemos/branches/advdemos/mpeg2/mpeg2dec.h
0,0 → 1,129
/* mpeg2dec.h, MPEG specific defines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#define ERROR (-1)
 
#define PICTURE_START_CODE 0x100
#define SLICE_START_CODE_MIN 0x101
#define SLICE_START_CODE_MAX 0x1AF
#define USER_DATA_START_CODE 0x1B2
#define SEQUENCE_HEADER_CODE 0x1B3
#define SEQUENCE_ERROR_CODE 0x1B4
#define EXTENSION_START_CODE 0x1B5
#define SEQUENCE_END_CODE 0x1B7
#define GROUP_START_CODE 0x1B8
#define SYSTEM_START_CODE_MIN 0x1B9
#define SYSTEM_START_CODE_MAX 0x1FF
 
#define ISO_END_CODE 0x1B9
#define PACK_START_CODE 0x1BA
#define SYSTEM_START_CODE 0x1BB
 
#define VIDEO_ELEMENTARY_STREAM 0x1e0
 
/* scalable_mode */
#define SC_NONE 0
#define SC_DP 1
#define SC_SPAT 2
#define SC_SNR 3
#define SC_TEMP 4
 
/* picture coding type */
#define I_TYPE 1
#define P_TYPE 2
#define B_TYPE 3
#define D_TYPE 4
 
/* picture structure */
#define TOP_FIELD 1
#define BOTTOM_FIELD 2
#define FRAME_PICTURE 3
 
/* macroblock type */
#define MACROBLOCK_INTRA 1
#define MACROBLOCK_PATTERN 2
#define MACROBLOCK_MOTION_BACKWARD 4
#define MACROBLOCK_MOTION_FORWARD 8
#define MACROBLOCK_QUANT 16
#define SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG 32
#define PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS 64
 
 
/* motion_type */
#define MC_FIELD 1
#define MC_FRAME 2
#define MC_16X8 2
#define MC_DMV 3
 
/* mv_format */
#define MV_FIELD 0
#define MV_FRAME 1
 
/* chroma_format */
#define CHROMA420 1
#define CHROMA422 2
#define CHROMA444 3
 
/* extension start code IDs */
 
#define SEQUENCE_EXTENSION_ID 1
#define SEQUENCE_DISPLAY_EXTENSION_ID 2
#define QUANT_MATRIX_EXTENSION_ID 3
#define COPYRIGHT_EXTENSION_ID 4
#define SEQUENCE_SCALABLE_EXTENSION_ID 5
#define PICTURE_DISPLAY_EXTENSION_ID 7
#define PICTURE_CODING_EXTENSION_ID 8
#define PICTURE_SPATIAL_SCALABLE_EXTENSION_ID 9
#define PICTURE_TEMPORAL_SCALABLE_EXTENSION_ID 10
 
#define ZIG_ZAG 0
 
#define PROFILE_422 (128+5)
#define MAIN_LEVEL 8
 
/* Layers: used by Verbose_Flag, Verifier_Flag, Stats_Flag, and Trace_Flag */
#define NO_LAYER 0
#define SEQUENCE_LAYER 1
#define PICTURE_LAYER 2
#define SLICE_LAYER 3
#define MACROBLOCK_LAYER 4
#define BLOCK_LAYER 5
#define EVENT_LAYER 6
#define ALL_LAYERS 7
 
 
 
#define FILENAME_LENGTH 256
 
 
 
 
#define MB_WEIGHT 32
#define MB_CLASS4 64
 
/advdemos/branches/advdemos/mpeg2/store.c
0,0 → 1,529
/* store.c, picture output routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
 
#include "config.h"
#include "global.h"
#include "semaphore.h"
#include "kernel/kern.h"
 
//#debug DEBUG_MAILBOX
 
static void conv422to444 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
static void conv420to422 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
 
__inline__ WORD down32to16(unsigned char r, unsigned char g, unsigned char b)
{
return ((b&0xf8)>>3)|((g&0xfc)<<3)|((r&0xf8)<<8);
}
 
#if 0
void xWrite_Frame _ANSI_ARGS_((unsigned char *src[], int frame))
{
int i, j;
int y, u, v, r, g, b;
// int rm=0,gm=0,bm=0;
int crv, cbu, cgu, cgv;
unsigned char *py, *pu, *pv;
int height, width;
 
struct framebuf_struct *f;
 
cprintf("%d ",frame);
 
width = Coded_Picture_Width ;
height= Coded_Picture_Height;
 
f = get_free_framebuf();
 
dither(src);
f->f[i*width+j] = down32to16(r,g,b);
f->n = frame;
insert_frame(f);
}
#endif
 
void Write_Frame _ANSI_ARGS_((unsigned char *src[], int frame))
{
int i, j;
int y, u, v, r, g, b;
// int rm=0,gm=0,bm=0;
int crv, cbu, cgu, cgv;
unsigned char *py, *pu, *pv;
int height, width, incr;
static unsigned char *u422, *v422, *u444, *v444;
 
struct framebuf_struct *f;
 
cprintf("%d ",frame);
 
incr = width = Coded_Picture_Width ;
height= Coded_Picture_Height;
 
if (chroma_format==CHROMA444)
{
u444 = src[1];
v444 = src[2];
}
else
{
if (!u444)
{
if (chroma_format==CHROMA420)
{
if (!(u422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
if (!(v422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (!(u444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
 
if (!(v444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (chroma_format==CHROMA420)
{
conv420to422(src[1],u422);
conv420to422(src[2],v422);
conv422to444(u422,u444);
conv422to444(v422,v444);
}
else
{
conv422to444(src[1],u444);
conv422to444(src[2],v444);
}
}
 
 
f = get_free_framebuf();
 
/* matrix coefficients */
crv = Inverse_Table_6_9[matrix_coefficients][0];
cbu = Inverse_Table_6_9[matrix_coefficients][1];
cgu = Inverse_Table_6_9[matrix_coefficients][2];
cgv = Inverse_Table_6_9[matrix_coefficients][3];
for (i=0; i<height; i++)
{
py = src[0] + incr*i;
pu = u444 + incr*i;
pv = v444 + incr*i;
 
for (j=0; j<width; j++)
{
u = *pu++ - 128;
v = *pv++ - 128;
y = 76309 * (*py++ - 16); /* (255/219)*65536 */
 
r = Clip[(y + crv*v + 32768)>>16];
g = Clip[(y - cgu*u - cgv*v + 32768)>>16];
b = Clip[(y + cbu*u + 32786)>>16];
 
// rm = max(rm,r);gm=max(gm,g);bm=max(bm,b);
// cprintf("(r%dg%db%d)",rm,gm,bm);
f->f[i*width+j] = down32to16(r,g,b);
// r=g=b=rand()%255;
// f->f[i*width+j] = down32to16(r,g,b);
}
}
f->n = frame;
insert_frame(f);
}
 
/*
void Display_Image(Dithered_Image)
unsigned char *Dithered_Image;
{
/ * display dithered image */
//}
 
 
/* horizontal 1:2 interpolation filter */
static void conv422to444(src,dst)
unsigned char *src,*dst;
{
int i, i2, w, j, im3, im2, im1, ip1, ip2, ip3;
 
w = Coded_Picture_Width>>1;
 
if (base.MPEG2_Flag)
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
i2 = i<<1;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 21 0 -52 0 159 256 159 0 -52 0 21 */
/* even samples (0 0 256 0 0) */
dst[i2] = src[i];
 
/* odd samples (21 -52 159 159 -52 21) */
dst[i2+1] = Clip[(int)(21*(src[im2]+src[ip3])
-52*(src[im1]+src[ip2])
+159*(src[i]+src[ip1])+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
else
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
 
i2 = i<<1;
im3 = (i<3) ? 0 : i-3;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
dst[i2] = Clip[(int)( 5*src[im3]
-21*src[im2]
+70*src[im1]
+228*src[i]
-37*src[ip1]
+11*src[ip2]+128)>>8];
 
dst[i2+1] = Clip[(int)( 5*src[ip3]
-21*src[ip2]
+70*src[ip1]
+228*src[i]
-37*src[im1]
+11*src[im2]+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
}
 
/* vertical 1:2 interpolation filter */
static void conv420to422(src,dst)
unsigned char *src,*dst;
{
int w, h, i, j, j2;
int jm6, jm5, jm4, jm3, jm2, jm1, jp1, jp2, jp3, jp4, jp5, jp6, jp7;
 
w = Coded_Picture_Width>>1;
h = Coded_Picture_Height>>1;
 
if (progressive_frame)
{
/* intra frame */
for (i=0; i<w; i++)
{
for (j=0; j<h; j++)
{
j2 = j<<1;
jm3 = (j<3) ? 0 : j-3;
jm2 = (j<2) ? 0 : j-2;
jm1 = (j<1) ? 0 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp2 = (j<h-2) ? j+2 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
/* New FIR filter coefficients (*256): 3 -16 67 227 -32 7 */
dst[w*j2] = Clip[(int)( 3*src[w*jm3]
-16*src[w*jm2]
+67*src[w*jm1]
+227*src[w*j]
-32*src[w*jp1]
+7*src[w*jp2]+128)>>8];
 
dst[w*(j2+1)] = Clip[(int)( 3*src[w*jp3]
-16*src[w*jp2]
+67*src[w*jp1]
+227*src[w*j]
-32*src[w*jm1]
+7*src[w*jm2]+128)>>8];
}
src++;
dst++;
}
}
else
{
/* intra field */
for (i=0; i<w; i++)
{
for (j=0; j<h; j+=2)
{
j2 = j<<1;
 
/* top field */
jm6 = (j<6) ? 0 : j-6;
jm4 = (j<4) ? 0 : j-4;
jm2 = (j<2) ? 0 : j-2;
jp2 = (j<h-2) ? j+2 : h-2;
jp4 = (j<h-4) ? j+4 : h-2;
jp6 = (j<h-6) ? j+6 : h-2;
 
/* Polyphase FIR filter coefficients (*256): 2 -10 35 242 -18 5 */
/* New polyphase FIR filter coefficients (*256): 1 -7 30 248 -21 5 */
dst[w*j2] = Clip[(int)( 1*src[w*jm6]
-7*src[w*jm4]
+30*src[w*jm2]
+248*src[w*j]
-21*src[w*jp2]
+5*src[w*jp4]+128)>>8];
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+2)] = Clip[(int)( 7*src[w*jm4]
-35*src[w*jm2]
+194*src[w*j]
+110*src[w*jp2]
-24*src[w*jp4]
+4*src[w*jp6]+128)>>8];
 
/* bottom field */
jm5 = (j<5) ? 1 : j-5;
jm3 = (j<3) ? 1 : j-3;
jm1 = (j<1) ? 1 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
jp5 = (j<h-5) ? j+5 : h-1;
jp7 = (j<h-7) ? j+7 : h-1;
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+1)] = Clip[(int)( 7*src[w*jp5]
-35*src[w*jp3]
+194*src[w*jp1]
+110*src[w*jm1]
-24*src[w*jm3]
+4*src[w*jm5]+128)>>8];
 
dst[w*(j2+3)] = Clip[(int)( 1*src[w*jp7]
-7*src[w*jp5]
+30*src[w*jp3]
+248*src[w*jp1]
-21*src[w*jm1]
+5*src[w*jm3]+128)>>8];
}
src++;
dst++;
}
}
}
 
 
 
 
 
// Frame buffer for displaying pictures
 
struct framebuf_struct *get_free_framebuf();
void insert_frame(struct framebuf_struct *f);
struct framebuf_struct *remove_frame();
 
int framebuf_sz;
 
// a queue of framebufs
struct framebuf_struct *framebuf_first;
struct framebuf_struct *framebuf_last;
 
// free framebuf list
struct framebuf_struct *framebuf_free;
 
// some semaphores
sem_t framebuf_sem;
sem_t framebuf_count;
sem_t framebuf_freecount;
 
void allocate_framebuf()
{
struct framebuf_struct *f;
 
f = (struct framebuf_struct *)malloc(sizeof(struct framebuf_struct));
if (!f) {
cputs("Not enough memory!!!\n");
sys_end();
}
 
f->f = (WORD *)malloc(framebuf_sz);
if (!f->f) {
cputs("Not enough memory for buffer!!!\n");
sys_end();
}
 
f->next = framebuf_free;
framebuf_free = f;
cprintf("(Alloc %d %d)\n",f,f->f);
}
 
void Initialize_framebuf(int sz)
{
int i;
 
framebuf_first = NULL;
framebuf_last = NULL;
framebuf_free = NULL;
framebuf_sz = sz;
 
cprintf("Coded W=%d H=%d sz=%d\n",Coded_Picture_Width,Coded_Picture_Height,sz);
 
for (i=0; i<MAX_FRAMEBUF; i++)
allocate_framebuf();
 
sem_init(&framebuf_sem,0,1);
sem_init(&framebuf_count,0,0);
sem_init(&framebuf_freecount,0,MAX_FRAMEBUF);
}
 
struct framebuf_struct *get_free_framebuf()
{
struct framebuf_struct *f;
 
#ifdef DEBUG_MAILBOX
cprintf("G");
#endif
sem_wait(&framebuf_freecount);
sem_wait(&framebuf_sem);
 
//if (!framebuf_free)
// allocate_framebuf();
 
f = framebuf_free;
 
framebuf_free = framebuf_free->next;
 
sem_post(&framebuf_sem);
 
return f;
}
 
void insert_frame(struct framebuf_struct *f)
{
struct framebuf_struct *p, *q;
int n;
 
#ifdef DEBUG_MAILBOX
cprintf("I");
#endif
sem_wait(&framebuf_sem);
 
p = NULL;
q = framebuf_first;
n = f->n;
 
while ((q != NULL) && (n >= q->n)) {
p = q;
q = q->next;
}
 
if (p)
p->next = f;
else
framebuf_first = f;
 
if (q)
q->prev = f;
else
framebuf_last = f;
 
f->next = q;
f->prev = p;
 
sem_post(&framebuf_count);
sem_post(&framebuf_sem);
}
 
struct framebuf_struct *remove_frame()
{
struct framebuf_struct *f;
 
#ifdef DEBUG_MAILBOX
cprintf("R");
#endif
sem_wait(&framebuf_count);
sem_wait(&framebuf_sem);
 
 
// remove the first frame
f = framebuf_first;
 
if (!f)
sys_abort(69); // should never happen
 
framebuf_first = framebuf_first->next;
 
if (framebuf_first)
framebuf_first->prev = NULL;
else
framebuf_last = NULL;
 
sem_post(&framebuf_sem);
 
return f;
}
 
void give_back_framebuf(struct framebuf_struct *f)
{
#ifdef DEBUG_MAILBOX
cprintf("B");
#endif
sem_wait(&framebuf_sem);
 
f->next = framebuf_free;
framebuf_free = f;
 
sem_post(&framebuf_sem);
sem_post(&framebuf_freecount);
}
 
 
 
 
 
/advdemos/branches/advdemos/mpeg2/makefile
0,0 → 1,19
#
# The mpeg library
#
 
# (see sources for copyrights)
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
PROGS= mpeg2dec
 
include $(BASE)/config/example.mk
 
OBJS= "initfile.o jetctrl.o getpic.o motion.o getvlc.o gethdr.o getblk.o getbits.o store.o recon.o spatscal.o idct.o idctref.o systems.o subspic.o verify.o gvideo.o"
 
mpeg2dec:
make -f $(SUBMAKE) APP=mpeg2dec INIT= OTHEROBJS=$(OBJS) OTHERINCL= SHARKOPT="__OLDCHAR__ __GRX__"
/advdemos/branches/advdemos/mpeg2/examples
0,0 → 1,49
EXAMPLES:
 
1. to decode a bitstream with double precision IDCT, such as
to create a reference reconstruction set of frames:
 
mpeg2decode -r -f -o0 rec%d -b bitstream.mpg
 
2. to decode a bitstream with fast integer IDCT, such as
to create a test reconstruction set of frames:
 
mpeg2decode -f -o0 rec%d -b bitstream.mpg
 
3. To substitute reference pictures with external reference
pictures (ref%d):
 
mpeg2decode -f -x ref%d -b bitstream.mpg -o0 rec%d
 
 
4. Same as 3. only using a single large concatenated file for the
sequence of reconstruction frames.
 
mpeg2decode -f -g -x ref%d bitstream.mpg -o0 rec%d
 
5. Decode an SNR enhancement bitstream at the same time as base layer
stream:
 
mpeg2decode -o0 rec%d -e snr_bitstream.mpg -b base_bitstream.mpg
 
6. Decode a Spatially scalable bitstream
 
Step 1: create lower layer reconstruction
 
mpeg2decode -f -o0 llrec%d -b base_layer.mpg
 
Step 2: decode enhancement bitstream, combined reconstruction.
 
mpeg2decode -f -l llrec%d -b enhancement_layer.mpg -o0 rec%d
 
------------
where:
-o0 specifies .Y, .U, .V input
-f specifies field interleaved format
-b is the bitstream flag
-g specifies substitute file is a large concatendated one.
-e substitution flag
ref.pic filename of substitution sequence
bitstream.mpg bitstream
test%d output file pattern
 
/advdemos/branches/advdemos/rtw/control.c
0,0 → 1,67
#include "kernel/kern.h"
#include "modules/cabs.h"
 
#include "tmwtypes.h"
 
#include "rtw.h"
 
extern CAB input_cid[NINPUTCAB];
 
TASK CONTROL_body(void *arg) {
 
real_T *p;
input_cid[0] = cab_create("INPUT0", sizeof(real_T), 2);
input_cid[1] = cab_create("INPUT1", sizeof(real_T), 2);
while(1) {
/* Reserve a message */
p = (real_T *)cab_reserve(input_cid[0]);
/* Save PAR1 data */
*p = 1000.0;
/* Put CAB message */
cab_putmes(input_cid[0], p);
 
/* Reserve a message */
p = (real_T *)cab_reserve(input_cid[1]);
/* Save PAR2 data */
*p = 1000.0;
/* Put CAB message */
cab_putmes(input_cid[1], p);
task_endcycle();
}
return NULL;
 
}
 
void activate_control() {
 
HARD_TASK_MODEL CONTROL_task;
PID CONTROL_pid;
 
hard_task_default_model(CONTROL_task);
hard_task_def_mit(CONTROL_task,10000);
hard_task_def_wcet(CONTROL_task,500);
hard_task_def_usemath(CONTROL_task);
hard_task_def_ctrl_jet(CONTROL_task);
CONTROL_pid = task_create("CONTROL",CONTROL_body,&CONTROL_task,NULL);
if (CONTROL_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [CONTROL] Task\n");
sys_end();
}
 
task_activate(CONTROL_pid);
 
}
 
 
 
/advdemos/branches/advdemos/rtw/rtw.h
0,0 → 1,10
#ifndef __RTW_H__
#define __RTW_H__
 
#define NINPUTCAB 10
#define NOUTPUTCAB 10
 
void activate_sensors();
void activate_control();
 
#endif
/advdemos/branches/advdemos/rtw/percorso.h
0,0 → 1,48
#ifndef __PERCORSO_H__
#define __PERCORSO_H__
 
#define PATH_ELEM_ARC 1
#define PATH_ELEM_LINE 2
 
#define CLOCKWISE -1
#define COUNTERCLOCK 1
 
typedef struct point {
double x,y;
} POINT;
 
typedef struct path_elem {
int type;
void *data;
struct path_elem *next;
} PATH_ELEM;
 
typedef struct pd_arc {
POINT c;
double r;
double alpha1;
double alpha2;
int dir;
} PATH_DATA_ARC;
 
typedef struct pd_line {
POINT p1;
POINT p2;
double alpha;
int dir;
} PATH_DATA_LINE;
 
 
PATH_ELEM *find_closest_elem(POINT *p, double radius);
double get_distance_from_elem(POINT *p, PATH_ELEM *e);
double get_angle_from_elem(POINT *p, PATH_ELEM *e);
/* ritorna:
1 : curva a sinistra
-1 : curva a destra
0 : dritto
*/
int is_curve(PATH_ELEM *e);
 
void Init_All_Path();
 
#endif
/advdemos/branches/advdemos/rtw/initfile.c
0,0 → 1,120
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
------------
CVS : $Id: initfile.c,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
System initialization file
 
This file contains the 2 functions needed to initialize the system.
 
These functions register the following levels:
 
an EDF (Earliest Deadline First) level
a RR (Round Robin) level
a CBS (Costant Bandwidth Server) level
a Dummy level
 
It can accept these task models:
 
HARD_TASK_MODEL (wcet+mit) at level 0
SOFT_TASK_MODEL (met, period) at level 1
NRT_TASK_MODEL at level 2
 
This file is similar to the configuration of kernel/init/hartik3.c
 
TICK is set to 0 (one-shot timer is used)
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "modules/rr.h"
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
 
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDF_register_level(EDF_ENABLE_ALL);
CBS_register_level(CBS_ENABLE_ALL, 0);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
dummy_register_level();
 
SEM_register_module();
 
CABS_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
KEYB_PARMS kparms = BASE_KEYB;
 
HARTPORT_init();
 
keyb_def_ctrlC(kparms, NULL);
keyb_def_map(kparms,itaMap);
KEYB_init(&kparms);
 
__call_main__(mb);
 
return (void *)0;
}
 
/advdemos/branches/advdemos/rtw/actuators.c
0,0 → 1,62
#include "kernel/kern.h"
#include "modules/cabs.h"
 
#include "tmwtypes.h"
 
#include "rtw.h"
 
extern CAB output_cid[NOUTPUTCAB];
 
TASK ACTUATOR_body(void *output_port) {
 
real_T *p, value;
int out = (int)(output_port);
if (out >= NOUTPUTCAB) return NULL;
while(1) {
/* Get CAB message */
p = (real_T *)cab_getmes(output_cid[out]);
/* Set value */
value = *p;
/* Release CAB message */
cab_unget(output_cid[out], p);
 
cprintf("Value = %lf\n",value);
task_endcycle();
}
return NULL;
 
}
 
void activate_actuators() {
 
HARD_TASK_MODEL ACTUATOR_task;
PID ACTUATOR_pid;
 
hard_task_default_model(ACTUATOR_task);
hard_task_def_mit(ACTUATOR_task,20000);
hard_task_def_wcet(ACTUATOR_task,4000);
/* Set actuator port number */
hard_task_def_arg(ACTUATOR_task,(void *)(0));
hard_task_def_usemath(ACTUATOR_task);
hard_task_def_ctrl_jet(ACTUATOR_task);
ACTUATOR_pid = task_create("ACTUATOR0",ACTUATOR_body,&ACTUATOR_task,NULL);
if (ACTUATOR_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [ACTUATOR0] Task\n");
sys_end();
}
 
task_activate(ACTUATOR_pid);
 
}
 
 
 
/advdemos/branches/advdemos/rtw/rt_sim_shark.c
0,0 → 1,385
#include <math.h>
 
#include "tmwtypes.h"
#ifdef USE_RTMODEL
# include "simstruc_types.h"
#else
# include "simstruc.h"
#endif
#include "rt_sim.h"
 
#include "kernel/kern.h"
 
#ifndef RT_MALLOC /* statically declare data */
 
/*==========*
* Struct's *
*==========*/
 
/*
* TimingData
*/
typedef struct TimingData_Tag {
real_T period[NUMST]; /* Task periods in seconds */
real_T offset[NUMST]; /* Task offsets in seconds */
real_T clockTick[NUMST]; /* Flint task time tick counter */
int_T taskTick[NUMST]; /* Counter for determining task hits */
int_T nTaskTicks[NUMST]; /* Number base rate ticks for a task hit */
int_T firstDiscIdx; /* First discrete task index */
} TimingData;
 
/*=========================*
* Data local to this file *
*=========================*/
 
static TimingData td;
 
/*==================*
* Visible routines *
*==================*/
 
/* Function: rt_SimInitTimingEngine ============================================
* Abstract:
* This function is for use with single tasking or multitasking
* real-time systems.
*
* Initializes the timing engine for a fixed-step real-time system.
* It is assumed that start time is 0.0.
*
* Returns:
* NULL - success
* non-NULL - error string
*/
const char *rt_SimInitTimingEngine(int_T rtmNumSampTimes,
real_T rtmStepSize,
real_T *rtmSampleTimePtr,
real_T *rtmOffsetTimePtr,
int_T *rtmSampleHitPtr,
int_T *rtmSampleTimeTaskIDPtr,
real_T rtmTStart,
SimTimeStep *rtmSimTimeStepPtr,
void **rtmTimingDataPtr)
{
int_T i;
int *tsMap = rtmSampleTimeTaskIDPtr;
real_T *period = rtmSampleTimePtr;
real_T *offset = rtmOffsetTimePtr;
int_T *sampleHit = rtmSampleHitPtr;
real_T stepSize = rtmStepSize;
 
if (rtmTStart != 0.0) {
return("Start time must be zero for real-time systems");
}
 
*rtmSimTimeStepPtr = MAJOR_TIME_STEP;
 
*rtmTimingDataPtr = (void*)&td;
 
for (i = 0; i < NUMST; i++) {
tsMap[i] = i;
td.period[i] = period[i];
td.offset[i] = offset[i];
td.nTaskTicks[i] = (int_T)floor(period[i]/stepSize + 0.5);
if (td.period[i] == CONTINUOUS_SAMPLE_TIME ||
td.offset[i] == 0.0) {
td.taskTick[i] = 0;
td.clockTick[i] = 0.0;
sampleHit[i] = 1;
} else {
td.taskTick[i] = (int_T)floor((td.period[i]-td.offset[i]) /
stepSize+0.5);
td.clockTick[i] = -1.0;
sampleHit[i] = 0;
}
}
 
/* Correct first sample time if continuous task */
td.period[0] = stepSize;
td.nTaskTicks[0] = 1;
 
/* Set first discrete task index */
#if NUMST == 1
td.firstDiscIdx = (int_T)(period[0] == CONTINUOUS_SAMPLE_TIME);
#else
td.firstDiscIdx = ((int_T)(period[0] == CONTINUOUS_SAMPLE_TIME) +
(int_T)(period[1] == CONTINUOUS_SAMPLE_TIME));
#endif
 
return(NULL); /* success */
 
} /* end rt_SimInitTimingEngine */
 
 
#if !defined(MULTITASKING)
 
/*###########################################################################*/
/*########################### SINGLE TASKING ################################*/
/*###########################################################################*/
 
/* Function: rt_SimGetNextSampleHit ============================================
* Abstract:
* For a single tasking real-time system, return time of next sample hit.
*/
time_T rt_SimGetNextSampleHit(void)
{
time_T timeOfNextHit;
td.clockTick[0] += 1;
timeOfNextHit = td.clockTick[0] * td.period[0];
 
# if NUMST > 1
{
int i;
for (i = 1; i < NUMST; i++) {
if (++td.taskTick[i] == td.nTaskTicks[i]) {
td.taskTick[i] = 0;
td.clockTick[i]++;
}
}
}
# endif
 
return(timeOfNextHit);
 
} /* end rt_SimGetNextSampleHit */
 
 
 
/* Function: rt_SimUpdateDiscreteTaskSampleHits ================================
* Abstract:
* This function is for use with single tasking real-time systems.
*
* If the number of sample times is greater than one, then we need to
* update the discrete task sample hits for the next time step. Note,
* task 0 always has a hit since it's sample time is the fundamental
* sample time.
*/
void rt_SimUpdateDiscreteTaskSampleHits(int_T rtmNumSampTimes,
void *rtmTimingData,
int_T *rtmSampleHitPtr,
real_T *rtmTPtr)
{
int_T *sampleHit = rtmSampleHitPtr;
int i;
UNUSED_PARAMETER(rtmTimingData);
UNUSED_PARAMETER(rtmNumSampTimes);
for (i = td.firstDiscIdx; i < NUMST; i++) {
int_T hit = (td.taskTick[i] == 0);
if (hit) {
rttiSetTaskTime(rtmTPtr, i,
td.clockTick[i]*td.period[i] + td.offset[i]);
}
sampleHit[i] = hit;
}
} /* rt_SimUpdateDiscreteTaskSampleHits */
 
 
 
#else /* defined(MULTITASKING) */
 
/*###########################################################################*/
/*############################## MULTITASKING ###############################*/
/*###########################################################################*/
 
 
/* Function: rt_SimUpdateDiscreteEvents ========================================
* Abstract:
* This function is for use with multitasking real-time systems.
*
* This function updates the status of the RT_MODEL sampleHits
* flags and the perTaskSampleHits matrix which is used to determine
* when special sample hits occur.
*
* The RT_MODEL contains a matrix, called perTaskSampleHits.
* This matrix is used by the ssIsSpecialSampleHit macro. The row and
* column indices are both task id's (equivalent to the root RT_MODEL
* sample time indices). This is a upper triangle matrix. This routine
* only updates the slower task hits (kept in column j) for row
* i if we have a sample hit in row i.
*
* column j
* tid 0 1 2 3 4 5
* -------------------------
* 0 | | X | X | X | X | X |
* r -------------------------
* o 1 | | | X | X | X | X | This matrix(i,j) answers:
* w ------------------------- If we are in task i, does
* 2 | | | | X | X | X | slower task j have a hit now?
* i -------------------------
* 3 | | | | | X | X |
* -------------------------
* 4 | | | | | | X | X = 0 or 1
* -------------------------
* 5 | | | | | | |
* -------------------------
*
* How macros index this matrix:
*
* ssSetSampleHitInTask(S, j, i, X) => matrix(i,j) = X
*
* ssIsSpecialSampleHit(S, my_sti, promoted_sti, tid) =>
* (tid_for(promoted_sti) == tid && !minor_time_step &&
* matrix(tid,tid_for(my_sti))
* )
*
* my_sti = My (the block's) original sample time index.
* promoted_sti = The block's promoted sample time index resulting
* from a transition via a ZOH from a fast to a
* slow block or a transition via a unit delay from
* a slow to a fast block.
*
* The perTaskSampleHits array, of dimension n*n, is accessed using
* perTaskSampleHits[j + i*n] where n is the total number of sample
* times, 0 <= i < n, and 0 <= j < n. The C language stores arrays in
* row-major order, that is, row 0 followed by row 1, etc.
*
*/
time_T rt_SimUpdateDiscreteEvents(int_T rtmNumSampTimes,
void *rtmTimingData,
int_T *rtmSampleHitPtr,
int_T *rtmPerTaskSampleHits)
{
int i, j;
int_T *sampleHit = rtmSampleHitPtr;
UNUSED_PARAMETER(rtmTimingData);
/*
* Run this loop in reverse so that we do lower priority events first.
*/
i = NUMST;
while (--i >= 0) {
if (td.taskTick[i] == 0) {
/*
* Got a sample hit, reset the counter, and update the clock
* tick counter.
*/
sampleHit[i] = 1;
td.clockTick[i]++;
 
/*
* Record the state of all "slower" events
*/
for (j = i + 1; j < NUMST; j++) {
rttiSetSampleHitInTask(rtmPerTaskSampleHits, rtmNumSampTimes,
j, i, sampleHit[j]);
}
} else {
/*
* no sample hit, increment the counter
*/
sampleHit[i] = 0;
}
 
if (++td.taskTick[i] == td.nTaskTicks[i]) { /* update for next time */
td.taskTick[i] = 0;
}
}
 
return(td.clockTick[0]*td.period[0]);
} /* rt_SimUpdateDiscreteEvents */
 
 
 
/* Function: rt_SimUpdateDiscreteTaskTime ======================================
* Abstract:
* This function is for use with multitasking systems.
*
* After a discrete task output and update has been performed, this
* function must be called to update the discrete task time for next
* time around.
*/
void rt_SimUpdateDiscreteTaskTime(real_T *rtmTPtr,
void *rtmTimingData,
int tid)
{
UNUSED_PARAMETER(rtmTimingData);
rttiSetTaskTime(rtmTPtr, tid,
td.clockTick[tid]*td.period[tid] + td.offset[tid]);
}
 
#endif /* MULTITASKING */
 
#else
 
#include "mrt_sim.c" /* dynamically allocate data */
 
#endif /* RT_MALLOC */
 
/*
*******************************************************************************
* FUNCTIONS MAINTAINED FOR BACKWARDS COMPATIBILITY WITH THE SimStruct
*******************************************************************************
*/
#ifndef USE_RTMODEL
const char *rt_InitTimingEngine(SimStruct *S)
{
const char_T *retVal = rt_SimInitTimingEngine(
ssGetNumSampleTimes(S),
ssGetStepSize(S),
ssGetSampleTimePtr(S),
ssGetOffsetTimePtr(S),
ssGetSampleHitPtr(S),
ssGetSampleTimeTaskIDPtr(S),
ssGetTStart(S),
&ssGetSimTimeStep(S),
&ssGetTimingData(S));
return(retVal);
}
 
# ifdef RT_MALLOC
void rt_DestroyTimingEngine(SimStruct *S)
{
rt_SimDestroyTimingEngine(ssGetTimingData(S));
}
# endif
 
# if !defined(MULTITASKING)
void rt_UpdateDiscreteTaskSampleHits(SimStruct *S)
{
rt_SimUpdateDiscreteTaskSampleHits(
ssGetNumSampleTimes(S),
ssGetTimingData(S),
ssGetSampleHitPtr(S),
ssGetTPtr(S));
}
 
# ifndef RT_MALLOC
 
time_T rt_GetNextSampleHit(void)
{
return(rt_SimGetNextSampleHit());
}
 
# else /* !RT_MALLOC */
 
time_T rt_GetNextSampleHit(SimStruct *S)
{
return(rt_SimGetNextSampleHit(ssGetTimingData(S),
ssGetNumSampleTimes(S)));
}
 
# endif
 
# else /* MULTITASKING */
 
time_T rt_UpdateDiscreteEvents(SimStruct *S)
{
return(rt_SimUpdateDiscreteEvents(
ssGetNumSampleTimes(S),
ssGetTimingData(S),
ssGetSampleHitPtr(S),
ssGetPerTaskSampleHitsPtr(S)));
}
 
void rt_UpdateDiscreteTaskTime(SimStruct *S, int tid)
{
rt_SimUpdateDiscreteTaskTime(ssGetTPtr(S), ssGetTimingData(S), tid);
}
 
#endif
#endif
 
/* EOF: rt_sim.c */
/advdemos/branches/advdemos/rtw/makefile
0,0 → 1,36
#
#
#
 
ifndef BASE
BASE=../..
endif
include $(BASE)/config/config.mk
 
MATLAB_RTW_DEMO_DIR = ./carrello0_grt_rtw/
 
DEFINE_MODEL = carrello0
DEFINE_NUMST = 2
DEFINE_NCSTATES = 7
DEFINE_TID01EQ = 1
DEFINE_RTWLIB += -lrtw
DEFINE_SOLVER = ode4.o
 
FILE_CODE = $(DEFINE_MODEL).o
FILE_DATA = $(DEFINE_MODEL)_data.o
 
PROGS = rtw
 
RTW_CFG = "-I. -I$(MATLAB_RTW_DEMO_DIR) -DUSE_RTMODEL -DRT -DMODEL=$(DEFINE_MODEL) -DNUMST=$(DEFINE_NUMST) -DNCSTATES=$(DEFINE_NCSTATES) -DTID01EQ=$(DEFINE_TID01EQ)"
 
RTW_OBJS = $(MATLAB_RTW_DEMO_DIR)/$(FILE_CODE) $(DEFINE_SOLVER) $(MODULES_rtwlib)
 
ifeq ($(FILE_DATA),$(DEFINE_MODEL)_data.o)
RTW_OBJS += $(MATLAB_RTW_DEMO_DIR)/$(FILE_DATA)
endif
 
include $(BASE)/config/example.mk
 
rtw:
make -f $(SUBMAKE) OTHERLIBS=$(DEFINE_RTWLIB) OTHERINCL=$(RTW_CFG) APP=rtw INIT= OTHEROBJS="initfile.o control.o sensors.o percorso.o rt_sim_shark.o $(RTW_OBJS)" SHARKOPT="__OLDCHAR__"
 
/advdemos/branches/advdemos/rtw/percorso.c
0,0 → 1,288
#include <stdio.h>
#include <math.h>
#include "percorso.h"
 
int nelem;
PATH_ELEM * head;
 
/* void print_elem(PATH_ELEM *elem) */
/* { */
/* if (elem->type == PATH_ELEM_ARC) { */
/* PATH_DATA_ARC *arc= (PATH_DATA_ARC *) elem->data; */
/* printf("Center: x =%3.3lf y =%3.3lf\n", arc->c.x, arc->c.y); */
/* printf("angles: a1=%3.3lf a2=%3.3lf\n", arc->alpha1, arc->alpha2); */
/* printf("Radius: r =%3.3lf\n", arc->r); */
/* } */
/* else if (elem->type == PATH_ELEM_LINE) { */
/* PATH_DATA_LINE *line = (PATH_DATA_LINE *) elem->data; */
/* printf("x1 = %3.3lf y1 = %3.3lf x2 = %3.3lf y2 = %3.3lf\n", */
/* line->p1.x, line->p1.y, line->p2.x, line->p2.y); */
/* } */
/* } */
 
/* void print_point(POINT *p) */
/* { */
/* printf("p.x = %3.3lf p.y = %3.3lf\n", p->x, p->y); */
/* } */
 
 
/*-----------------------------------------------------------------*/
 
inline double point_dist(POINT *p1, POINT *p2)
{
return sqrt((p1->x - p2->x)*(p1->x - p2->x) +
(p1->y - p2->y)*(p1->y - p2->y));
}
 
double get_angle_from_arc(POINT *p1, PATH_DATA_ARC *arc)
{
return acos((p1->x - arc->c.x) / point_dist(p1, &(arc->c)));
}
 
int inside_arc(PATH_DATA_ARC *arc, POINT *p)
{
double alpha = get_angle_from_arc(p, arc);
if (p->y < arc->c.y) alpha = 2*M_PI - alpha;
 
if (alpha <= arc->alpha2 && alpha >= arc->alpha1) return 1;
else return 0;
}
 
double get_distance_from_arc(POINT *p1, PATH_DATA_ARC *arc)
{
return point_dist (p1,&(arc->c)) - arc->r;
}
 
 
double get_distance_from_line(POINT *p, PATH_DATA_LINE *l)
{
return ((l->p1.y - l->p2.y) * p->x +
(l->p2.x - l->p1.x) * p->y +
(l->p1.x * l->p2.y - l->p2.x * l->p1.y)) /
point_dist(&(l->p1), &(l->p2));
}
 
 
inline double get_t(POINT *p, PATH_DATA_LINE *line)
{
double t = ( (line->p2.x - line->p1.x) * (p->x - line->p1.x) +
(line->p2.y - line->p1.y) * (p->y - line->p1.y)) /
(point_dist(&(line->p1), &(line->p2)) *
point_dist(&(line->p1), &(line->p2)));
return t;
}
 
 
double get_angle_from_line(POINT *p, PATH_DATA_LINE *l)
{
return atan2(l->p1.y - l->p2.y, l->p1.x - l->p2.x);
}
 
int includes_elem(POINT *p, PATH_ELEM *e, double radius)
{
if (e->type == PATH_ELEM_ARC) {
PATH_DATA_ARC *arc = (PATH_DATA_ARC *) e->data;
if (get_distance_from_arc(p, arc) <= radius && inside_arc(arc,p))
return 1;
else return 0;
}
else if (e->type==PATH_ELEM_LINE) {
PATH_DATA_LINE *line = (PATH_DATA_LINE *) e->data;
double t = get_t(p, line);
double d = get_distance_from_line(p, line);
if (t >= 0 && t <= 1 && d < radius) return 1;
else return 0;
}
return 0;
}
 
void init_arc(PATH_DATA_ARC *arc, double cx, double cy, double r,
double a1, double a2, int dir)
{
arc->c.x = cx;
arc->c.y = cy;
arc->r = r;
arc->alpha1 = a1;
arc->alpha2 = a2;
arc->dir = dir;
}
 
void init_line(PATH_DATA_LINE *l, double x1, double y1, double x2,
double y2, int dir)
{
//printf("%3.3lf %3.3lf %3.3lf %3.3lf \n", x1,y1,x2,y2);
l->p1.x = x1;
l->p2.x = x2;
l->p1.y = y1;
l->p2.y = y2;
l->dir = dir;
//printf("%3.3lf %3.3lf %3.3lf %3.3lf \n", l->p1.x,l->p1.y,l->p2.x,l->p2.y);
}
 
/*---------------------------------------------------------------*/
 
PATH_ELEM *find_closest_elem(POINT *p, double radius)
{
PATH_ELEM *cur = head;
int i = 0;
for (i=0; i<nelem; i++) {
//printf("Searching element %d \n", i);
//print_elem(cur);
if (includes_elem(p, cur, radius)) return cur;
else cur = cur->next;
}
return 0;
}
 
double get_distance_from_elem(POINT *p, PATH_ELEM *e)
{
double d = 0;
if (e->type == PATH_ELEM_ARC) {
PATH_DATA_ARC *arc = e->data;
d = get_distance_from_arc(p, arc);
}
else if (e->type == PATH_ELEM_LINE) {
PATH_DATA_LINE *line = e->data;
d = get_distance_from_line(p, line);
}
return d;
}
 
double get_angle_from_elem(POINT *p, PATH_ELEM *e)
{
double alpha = 0;
if (e->type == PATH_ELEM_ARC) {
PATH_DATA_ARC *arc = e->data;
alpha = get_angle_from_arc(p, arc) - M_PI/2;
}
else if (e->type == PATH_ELEM_LINE) {
PATH_DATA_LINE *line = e->data;
alpha = get_angle_from_line(p, line);
}
return alpha;
}
 
 
/* ritorna:
1 : curva a sinistra
-1 : curva a destra
0 : dritto */
int is_curve(PATH_ELEM *e)
{
if (e->type == PATH_ELEM_ARC) {
PATH_DATA_ARC *arc = e->data;
return arc->dir;
}
else return 0;
}
 
/*---------------------------------------------------------------*/
 
PATH_ELEM elems[11];
PATH_DATA_ARC arcs[6];
PATH_DATA_LINE lines[5];
 
void Init_All_Path()
{
init_line(&lines[0], 0,0,3,0, -1);
elems[0].type = PATH_ELEM_LINE;
elems[0].data = &lines[0];
elems[0].next = &elems[1];
 
init_arc(&arcs[0], 3,1, 1, -M_PI/2,0, 1);
elems[1].type = PATH_ELEM_ARC;
elems[1].data = &arcs[0];
elems[1].next = &elems[2];
 
init_line(&lines[1], 4,1,4,7, -1);
elems[2].type = PATH_ELEM_LINE;
elems[2].data = &lines[1];
elems[2].next = &elems[3];
 
init_arc(&arcs[1], 2,7, 2, 0, M_PI/2, 1);
elems[3].type = PATH_ELEM_ARC;
elems[3].data = &arcs[1];
elems[3].next = &elems[4];
 
init_line(&lines[2], 2,9,-1,9, 1);
elems[4].type = PATH_ELEM_LINE;
elems[4].data = &lines[2];
elems[4].next = &elems[5];
 
init_arc(&arcs[2], -2,8, 1, M_PI/2, M_PI, 1);
elems[5].type = PATH_ELEM_ARC;
elems[5].data = &arcs[2];
elems[5].next = &elems[6];
 
init_line(&lines[3], -3,8,-3,5, 1);
elems[6].type = PATH_ELEM_LINE;
elems[6].data = &lines[3];
elems[6].next = &elems[7];
 
init_arc(&arcs[3], -2,5, 1, M_PI, 3*M_PI/2, 1);
elems[7].type = PATH_ELEM_ARC;
elems[7].data = &arcs[3];
elems[7].next = &elems[8];
 
init_arc(&arcs[4], -2,3, 1, 0, M_PI/2, -1);
elems[8].type = PATH_ELEM_ARC;
elems[8].data = &arcs[4];
elems[8].next = &elems[9];
 
init_line(&lines[4], -1,3,-1,1, 1);
elems[9].type = PATH_ELEM_LINE;
elems[9].data = &lines[4];
elems[9].next = &elems[10];
 
init_arc(&arcs[5], 0,1, 1, M_PI, 3*M_PI/2, -1);
elems[10].type = PATH_ELEM_ARC;
elems[10].data = &arcs[5];
elems[10].next = &elems[0];
 
head = &elems[0];
nelem = 11;
}
 
 
/* int main(void) */
/* { */
/* double d; */
/* double alpha; */
/* POINT p; */
 
/* init_all(); */
 
/* p.x = -1.75; */
/* p.y = 4.25; */
 
/* PATH_ELEM *e = find_closest_elem(&p, head, 1); */
 
/* if (e != 0) { */
/* d = get_distance_from_elem(&p, e); */
/* alpha = get_angle_from_elem(&p, e); */
/* print_elem(e); */
/* printf("distance : %3.3lf alpha %3.3lf\n", d, alpha); */
/* printf("direzione %d\n", is_curve(e)); */
/* } */
/* else */
/* printf("Not found!\n"); */
 
 
/* p.x = 4.75; */
/* p.y = 7.1; */
/* e = find_closest_elem(&p, head, 1); */
 
/* if (e != 0) { */
/* d = get_distance_from_elem(&p, e); */
/* alpha = get_angle_from_elem(&p, e); */
/* print_elem(e); */
/* printf("distance : %3.3lf alpha %3.3lf\n", d, alpha); */
/* printf("direzione %d\n", is_curve(e)); */
/* } */
/* else */
/* printf("Not found!\n"); */
 
/* } */
/advdemos/branches/advdemos/rtw/rtw.c
0,0 → 1,585
#include "tmwtypes.h"
#include "rtmodel.h"
#include "rt_sim.h"
#include "rt_logging.h"
#include "rt_nonfinite.h"
 
#include "ext_work.h"
#include "rt_nonfinite.h"
 
#include "kernel/kern.h"
#include "modules/cabs.h"
#include "percorso.h"
 
#include "rtw.h"
 
/*=========*
* Defines *
*=========*/
 
#ifndef TRUE
#define FALSE (0)
#define TRUE (1)
#endif
 
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
 
#define QUOTE1(name) #name
#define QUOTE(name) QUOTE1(name) /* need to expand name */
 
#define RUN_FOREVER -1.0
 
#define EXPAND_CONCAT(name1,name2) name1 ## name2
#define CONCAT(name1,name2) EXPAND_CONCAT(name1,name2)
#define RT_MODEL CONCAT(MODEL,_rtModel)
 
extern RT_MODEL *MODEL(void);
extern void MdlInitializeSizes(void);
extern void MdlInitializeSampleTimes(void);
extern void MdlStart(void);
extern void MdlOutputs(int_T tid);
extern void MdlUpdate(int_T tid);
extern void MdlTerminate(void);
 
real_T rtInf;
real_T rtMinusInf;
real_T rtNaN;
 
CAB input_cid[NINPUTCAB];
CAB output_cid[NOUTPUTCAB];
 
#ifdef EXT_MODE
# define rtExtModeSingleTaskUpload(S) \
{ \
int stIdx; \
rtExtModeUploadCheckTrigger(); \
for (stIdx=0; stIdx<NUMST; stIdx++) { \
if (rtmIsSampleHit(S, stIdx, 0 /*unused*/)) { \
rtExtModeUpload(stIdx,rtmGetTaskTime(S,stIdx)); \
} \
} \
}
#else
# define rtExtModeSingleTaskUpload(S) /* Do nothing */
#endif
 
#if NCSTATES > 0
extern void rt_ODECreateIntegrationData(RTWSolverInfo *si);
extern void rt_ODEUpdateContinuousStates(RTWSolverInfo *si);
# define rt_CreateIntegrationData(S) \
rt_ODECreateIntegrationData(rtmGetRTWSolverInfo(S));
# define rt_UpdateContinuousStates(S) \
rt_ODEUpdateContinuousStates(rtmGetRTWSolverInfo(S));
# else
# define rt_CreateIntegrationData(S) \
rtsiSetSolverName(rtmGetRTWSolverInfo(S),"FixedStepDiscrete");
# define rt_UpdateContinuousStates(S) \
rtmSetT(S, rtsiGetSolverStopTime(rtmGetRTWSolverInfo(S)));
#endif
 
/*==================================*
* Global data local to this module *
*==================================*/
 
RT_MODEL *S;
const char *status;
real_T finaltime = -2.0;
volatile int simulation_run;
static struct {
int_T stopExecutionFlag;
int_T isrOverrun;
int_T overrunFlags[NUMST];
const char_T *errmsg;
} GBLbuf;
 
/* Function: rt_InitInfAndNaN ==================================================
* Abstract:
* Initialize the rtInf, rtMinusInf, and rtNaN needed by the
* generated code. NaN is initialized as non-signaling. Assumes IEEE.
*/
void rt_InitInfAndNaN(int_T realSize)
{
short one = 1;
enum {
LittleEndian,
BigEndian
} machByteOrder = (*((char *) &one) == 1) ? LittleEndian : BigEndian;
 
switch (realSize) {
case 4:
switch (machByteOrder) {
case LittleEndian: {
typedef struct {
uint32_T fraction : 23;
uint32_T exponent : 8;
uint32_T sign : 1;
} LittleEndianIEEEDouble;
(*(LittleEndianIEEEDouble*)&rtInf).sign = 0;
(*(LittleEndianIEEEDouble*)&rtInf).exponent = 0xFF;
(*(LittleEndianIEEEDouble*)&rtInf).fraction = 0;
rtMinusInf = rtInf;
rtNaN = rtInf;
(*(LittleEndianIEEEDouble*)&rtMinusInf).sign = 1;
(*(LittleEndianIEEEDouble*)&rtNaN).fraction = 0x7FFFFF;
}
break;
case BigEndian: {
typedef struct {
uint32_T sign : 1;
uint32_T exponent : 8;
uint32_T fraction : 23;
} BigEndianIEEEDouble;
(*(BigEndianIEEEDouble*)&rtInf).sign = 0;
(*(BigEndianIEEEDouble*)&rtInf).exponent = 0xFF;
(*(BigEndianIEEEDouble*)&rtInf).fraction = 0;
rtMinusInf = rtInf;
rtNaN = rtInf;
(*(BigEndianIEEEDouble*)&rtMinusInf).sign = 1;
(*(BigEndianIEEEDouble*)&rtNaN).fraction = 0x7FFFFF;
}
break;
}
break;
case 8:
switch (machByteOrder) {
case LittleEndian: {
typedef struct {
struct {
uint32_T fraction2;
} wordH;
struct {
uint32_T fraction1 : 20;
uint32_T exponent : 11;
uint32_T sign : 1;
} wordL;
} LittleEndianIEEEDouble;
(*(LittleEndianIEEEDouble*)&rtInf).wordL.sign = 0;
(*(LittleEndianIEEEDouble*)&rtInf).wordL.exponent = 0x7FF;
(*(LittleEndianIEEEDouble*)&rtInf).wordL.fraction1 = 0;
(*(LittleEndianIEEEDouble*)&rtInf).wordH.fraction2 = 0;
rtMinusInf = rtInf;
(*(LittleEndianIEEEDouble*)&rtMinusInf).wordL.sign = 1;
(*(LittleEndianIEEEDouble*)&rtNaN).wordL.sign = 0;
(*(LittleEndianIEEEDouble*)&rtNaN).wordL.exponent = 0x7FF;
(*(LittleEndianIEEEDouble*)&rtNaN).wordL.fraction1 = 0xFFFFF;
(*(LittleEndianIEEEDouble*)&rtNaN).wordH.fraction2 = 0xFFFFFFFF;
}
break;
case BigEndian: {
typedef struct {
struct {
uint32_T sign : 1;
uint32_T exponent : 11;
uint32_T fraction1 : 20;
} wordL;
struct {
uint32_T fraction2;
} wordH;
} BigEndianIEEEDouble;
(*(BigEndianIEEEDouble*)&rtInf).wordL.sign = 0;
(*(BigEndianIEEEDouble*)&rtInf).wordL.exponent = 0x7FF;
(*(BigEndianIEEEDouble*)&rtInf).wordL.fraction1 = 0;
(*(BigEndianIEEEDouble*)&rtInf).wordH.fraction2 = 0;
rtMinusInf = rtInf;
(*(BigEndianIEEEDouble*)&rtMinusInf).wordL.sign = 1;
(*(BigEndianIEEEDouble*)&rtNaN).wordL.sign = 0;
(*(BigEndianIEEEDouble*)&rtNaN).wordL.exponent = 0x7FF;
(*(BigEndianIEEEDouble*)&rtNaN).wordL.fraction1 = 0xFFFFF;
(*(BigEndianIEEEDouble*)&rtNaN).wordH.fraction2 = 0xFFFFFFFF;
}
break;
}
break;
default:
cprintf("Error: Unable to initialize rtInf, rtMinusInf and rtNaN\n");
sys_end();
break;
}
 
} /* end rt_InitInfAndNaN */
 
/* Function: rtOneStep ========================================================
*
* Abstract:
* Perform one step of the model. This function is modeled such that
* it could be called from an interrupt service routine (ISR) with minor
* modifications.
*/
static void rt_OneStep(RT_MODEL *S)
{
real_T tnext;
/***********************************************
* Check and see if base step time is too fast *
***********************************************/
if (GBLbuf.isrOverrun++) {
GBLbuf.stopExecutionFlag = 1;
return;
}
/***********************************************
* Check and see if error status has been set *
***********************************************/
if (rtmGetErrorStatus(S) != NULL) {
GBLbuf.stopExecutionFlag = 1;
return;
}
/* enable interrupts here */
rtExtModeOneStep(rtmGetRTWExtModeInfo(S),
(boolean_T *)&rtmGetStopRequested(S));
tnext = rt_SimGetNextSampleHit();
rtsiSetSolverStopTime(rtmGetRTWSolverInfo(S),tnext);
MdlOutputs(0);
rtExtModeSingleTaskUpload(S);
if (GBLbuf.errmsg != NULL) {
GBLbuf.stopExecutionFlag = 1;
return;
}
MdlUpdate(0);
rt_SimUpdateDiscreteTaskSampleHits(rtmGetNumSampleTimes(S),
rtmGetTimingData(S),
rtmGetSampleHitPtr(S),
rtmGetTPtr(S));
if (rtmGetSampleTime(S,0) == CONTINUOUS_SAMPLE_TIME) {
rt_UpdateContinuousStates(S);
}
GBLbuf.isrOverrun--;
rtExtModeCheckEndTrigger();
 
} /* end rtOneStep */
 
void Init_RealTime_Workshop() {
 
/****************************
* Initialize global memory *
****************************/
(void)memset(&GBLbuf, 0, sizeof(GBLbuf));
 
/************************
* Initialize the model *
************************/
rt_InitInfAndNaN(sizeof(real_T));
 
S = MODEL();
if (rtmGetErrorStatus(S) != NULL) {
cprintf("Error: Model registration: %s\n",
rtmGetErrorStatus(S));
sys_end();
}
if (finaltime >= 0.0 || finaltime == RUN_FOREVER) rtmSetTFinal(S,finaltime);
 
MdlInitializeSizes();
MdlInitializeSampleTimes();
status = rt_SimInitTimingEngine(rtmGetNumSampleTimes(S),
rtmGetStepSize(S),
rtmGetSampleTimePtr(S),
rtmGetOffsetTimePtr(S),
rtmGetSampleHitPtr(S),
rtmGetSampleTimeTaskIDPtr(S),
rtmGetTStart(S),
&rtmGetSimTimeStep(S),
&rtmGetTimingData(S));
 
if (status != NULL) {
cprintf("Error: Failed to initialize sample time engine: %s\n", status);
sys_end();
}
rt_CreateIntegrationData(S);
 
rtExtModeCheckInit();
rtExtModeWaitForStartMsg(rtmGetRTWExtModeInfo(S),
(boolean_T *)&rtmGetStopRequested(S));
 
cprintf("\n** Starting the model **\n");
 
MdlStart();
if (rtmGetErrorStatus(S) != NULL) {
GBLbuf.stopExecutionFlag = 1;
}
 
/*************************************************************************
* Execute the model. You may attach rtOneStep to an ISR, if so replace *
* the call to rtOneStep (below) with a call to a background task *
* application. *
*************************************************************************/
 
if (rtmGetTFinal(S) == RUN_FOREVER) {
cprintf("\n**May run forever. Model stop time set to infinity.**\n");
}
 
}
 
void Close_RealTime_Workshop() {
 
/********************
* Cleanup and exit *
********************/
 
rtExtModeShutdown();
 
if (GBLbuf.errmsg) {
cprintf("Error: %s\n",GBLbuf.errmsg);
sys_end();
}
 
if (GBLbuf.isrOverrun) {
cprintf("Error: %s: ISR overrun - base sampling rate is too fast\n",QUOTE(MODEL));
sys_end();
}
 
if (rtmGetErrorStatus(S) != NULL) {
cprintf("Error: %s\n", rtmGetErrorStatus(S));
sys_end();
}
 
MdlTerminate();
 
}
 
TASK RTW_body(void *arg) {
real_T *input, *p;
 
input = (real_T *)rtmGetU(S);
simulation_run = 1;
 
while (!GBLbuf.stopExecutionFlag &&
(rtmGetTFinal(S) == RUN_FOREVER ||
rtmGetTFinal(S)-rtmGetT(S) > rtmGetT(S)*DBL_EPSILON)) {
rtExtModePauseIfNeeded(rtmGetRTWExtModeInfo(S),
(boolean_T *)&rtmGetStopRequested(S));
if (rtmGetStopRequested(S)) break;
/* Get PAR0 */
if (input_cid[0] != -1) {
p = (real_T *)cab_getmes(input_cid[0]);
input[0] = *p;
cab_unget(input_cid[0], p);
}
 
/* Get PAR1 */
if (input_cid[1] != -1) {
p = (real_T *)cab_getmes(input_cid[1]);
input[1] = *p;
cab_unget(input_cid[1], p);
}
rt_OneStep(S);
 
task_endcycle();
 
}
 
if (!GBLbuf.stopExecutionFlag && !rtmGetStopRequested(S)) {
/* Execute model last time step */
rt_OneStep(S);
}
 
simulation_run = 0;
 
return NULL;
 
}
 
TASK OUTPUT_body(void *arg) {
 
real_T *output, *p;
real_T th;
 
POINT pos;
PATH_ELEM *e;
real_T distance = 0;
real_T angle = 0;
real_T curve = 0;
 
output_cid[0] = cab_create("DISTANCE", sizeof(real_T), 2);
output_cid[1] = cab_create("ANGLE", sizeof(real_T), 2);
output_cid[2] = cab_create("CURVE", sizeof(real_T), 2);
 
output = (real_T *)rtmGetY(S);
 
while(1) {
 
pos.x = output[0];
pos.y = output[1];
th = output[2];
e = find_closest_elem(&pos, 1.0);
if (e != 0) {
distance = get_distance_from_elem(&pos, e);
angle = th - get_angle_from_elem(&pos,e);
curve = is_curve(e);
}
/* Send Distance */
p = (real_T *)cab_reserve(output_cid[0]);
*p = distance;
cab_putmes(output_cid[0], p);
 
/* Send Angle */
p = (real_T *)cab_reserve(output_cid[1]);
*p = angle;
cab_putmes(output_cid[1], p);
 
/* Send Curve */
p = (real_T *)cab_reserve(output_cid[2]);
*p = curve;
cab_putmes(output_cid[2], p);
 
task_endcycle();
}
return NULL;
}
 
TASK OUTPUT_w_body(void *arg) {
 
real_T *output, *p;
 
real_T wr = 0;
real_T wl = 0;
 
output_cid[0] = cab_create("WR", sizeof(real_T), 2);
output_cid[1] = cab_create("WL", sizeof(real_T), 2);
 
output = (real_T *)rtmGetY(S);
 
while(1) {
 
wr = output[3];
wl = output[4];
/* Send wr */
p = (real_T *)cab_reserve(output_cid[3]);
*p = wr;
cab_putmes(output_cid[3], p);
 
/* Send wl */
p = (real_T *)cab_reserve(output_cid[4]);
*p = wl;
cab_putmes(output_cid[4], p);
 
task_endcycle();
 
}
 
return NULL;
 
}
 
void Init_Rtw() {
 
HARD_TASK_MODEL RTW_task,OUTPUT_task;
PID RTW_pid,OUTPUT_pid,OUTPUT_w_pid;
int i;
int RTW_period;
int RTW_wcet;
int OUTPUT_period;
int OUTPUT_wcet;
 
Init_RealTime_Workshop();
Init_All_Path();
 
for (i=0;i<NINPUTCAB;i++) input_cid[i] = -1;
for (i=0;i<NOUTPUTCAB;i++) output_cid[i] = -1;
RTW_period =(int)(rtmGetStepSize(S) * 1000000.0);
RTW_wcet = (int)(rtmGetStepSize(S) * 1000000.0 * 0.45);
OUTPUT_period = (int)(10000.0);
OUTPUT_wcet = (int)(10000.0 * 0.10);
cprintf("Task Setup\n");
cprintf("RTW (P %8d W %8d)\n",RTW_period,RTW_wcet);
cprintf("OUTPUT (P %8d W %8d)\n",OUTPUT_period,OUTPUT_wcet);
hard_task_default_model(RTW_task);
hard_task_def_mit(RTW_task,RTW_period);
hard_task_def_wcet(RTW_task,RTW_wcet);
hard_task_def_usemath(RTW_task);
hard_task_def_ctrl_jet(RTW_task);
RTW_pid = task_create("RTW",RTW_body,&RTW_task,NULL);
if (RTW_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [RTW] Task\n");
sys_end();
}
 
hard_task_default_model(OUTPUT_task);
hard_task_def_mit(OUTPUT_task,OUTPUT_period);
hard_task_def_wcet(OUTPUT_task,OUTPUT_wcet);
hard_task_def_usemath(OUTPUT_task);
hard_task_def_ctrl_jet(OUTPUT_task);
OUTPUT_pid = task_create("OUTPUT",OUTPUT_body,&OUTPUT_task,NULL);
if (OUTPUT_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [OUTPUT] Task\n");
sys_end();
}
hard_task_def_mit(OUTPUT_task,OUTPUT_period);
hard_task_def_wcet(OUTPUT_task,OUTPUT_wcet);
OUTPUT_w_pid = task_create("OUTPUTW",OUTPUT_w_body,&OUTPUT_task,NULL);
if (OUTPUT_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [OUTPUTW] Task\n");
sys_end();
}
task_activate(RTW_pid);
task_activate(OUTPUT_pid);
task_activate(OUTPUT_w_pid);
 
}
 
int main() {
 
Init_Rtw();
 
activate_sensors();
activate_control();
 
while(simulation_run);
Close_RealTime_Workshop();
 
sys_end();
 
return 0;
 
}
/advdemos/branches/advdemos/rtw/sensors.c
0,0 → 1,93
#include "kernel/kern.h"
#include "modules/cabs.h"
 
#include "tmwtypes.h"
 
#include "rtw.h"
 
extern CAB output_cid[NOUTPUTCAB];
 
TASK SENSOR_body(void *output_port) {
 
real_T *p, value;
int out = (int)(output_port);
if (out >= NOUTPUTCAB) return NULL;
while(1) {
/* Get CAB message */
p = (real_T *)cab_getmes(output_cid[out]);
/* Set value */
value = *p;
/* Release CAB message */
cab_unget(output_cid[out], p);
 
cprintf("Value %d = %lf\n",out,value);
task_endcycle();
}
return NULL;
 
}
 
void activate_sensors() {
 
HARD_TASK_MODEL SENSOR_task;
PID DISTANCE_pid,ANGLE_pid,CURVE_pid,WR_pid,WL_pid;
 
hard_task_default_model(SENSOR_task);
hard_task_def_mit(SENSOR_task,60000);
hard_task_def_wcet(SENSOR_task,4000);
hard_task_def_usemath(SENSOR_task);
hard_task_def_ctrl_jet(SENSOR_task);
hard_task_def_arg(SENSOR_task,(void *)(0));
DISTANCE_pid = task_create("DISTANCE",SENSOR_body,&SENSOR_task,NULL);
if (DISTANCE_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [DISTACE] Task\n");
sys_end();
}
 
hard_task_def_arg(SENSOR_task,(void *)(1));
ANGLE_pid = task_create("ANGLE",SENSOR_body,&SENSOR_task,NULL);
if (DISTANCE_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [DISTACE] Task\n");
sys_end();
}
 
hard_task_def_arg(SENSOR_task,(void *)(2));
CURVE_pid = task_create("CURVE",SENSOR_body,&SENSOR_task,NULL);
if (CURVE_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [CURVE] Task\n");
sys_end();
}
 
hard_task_def_arg(SENSOR_task,(void *)(3));
WR_pid = task_create("WR",SENSOR_body,&SENSOR_task,NULL);
if (WR_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [WR] Task\n");
sys_end();
}
 
hard_task_def_arg(SENSOR_task,(void *)(4));
WL_pid = task_create("CURVE",SENSOR_body,&SENSOR_task,NULL);
if (WR_pid == NIL) {
cprintf("Error: Cannot create RealTime Workshop [WL] Task\n");
sys_end();
}
task_activate(DISTANCE_pid);
task_activate(ANGLE_pid);
task_activate(CURVE_pid);
task_activate(WR_pid);
task_activate(WL_pid);
 
}
 
 
 
/advdemos/branches/advdemos/cash/testcash.c
0,0 → 1,455
/*
* Project: HARTIK (HA-rd R-eal TI-me K-ernel)
*
* Coordinators: Giorgio Buttazzo <giorgio@sssup.it>
* Gerardo Lamastra <gerardo@sssup.it>
*
* Authors : Paolo Gai <pj@hartik.sssup.it>
* (see authors.txt for full list of hartik's authors)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://hartik.sssup.it
*/
 
/**
------------
CVS : $Id: testcash.c,v 1.1.1.1 2004-05-24 17:54:49 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:49 $
------------
 
testcash.c
test for the CASH Module, directly derived from Test Number 13 (D)
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "cash.h"
#include <math.h>
#include <string.h>
 
#define ASTER_LIM 60
#define DISPLAY_MAX 15
 
#define STAT_Y 9
 
#define INPUT 0.5
 
 
 
#define MAX_STAT 10000
#define RVAL 1
#define XVAL 2
#define DVAL 3
 
 
struct statistic {
TIME r_time;
TIME ex_time;
long dead_post;
};
 
 
 
struct statistic stat[MAX_STAT];
TIME val[MAX_STAT];
 
int n_stat = 0;
 
TASK hard_asteroide(void)
{
int i;
int y = rand() % 7 + 1;
double avg, l, fix, u;
double wcet = 40200;
int load1,j;
 
char s[2];
 
s[0] = 'H'; s[1] = 0;
/* exponential distribution parameters */
fix = wcet - 10.0/9.0 * wcet * (1 - INPUT);
avg = 1.0/9.0 * wcet * (1 - INPUT);
l = 10.0 / 9.0 * wcet * (1 - INPUT);
for (;;) {
i = 1;
while (i < ASTER_LIM) {
/* exponential distribution */
u = (double)rand();
u = u / (double)RAND_MAX;
u = -avg * log(u);
if (u > l)
u = avg;
 
load1 = fix + u;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(1, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK hard_asteroide1(void)
{
int i;
int y = rand() % 7 + 1;
 
int load1,j;
 
char s[2];
 
s[0] = 'H'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 40000 + rand()%20000;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(1, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK hard_asteroide2(void)
{
int i;
int y = rand() % 7 + 1;
 
int load1,j;
 
char s[2];
 
s[0] = 'H'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 80500; // + rand()%6000;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(5, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
TASK hard_asteroide3(void)
{
int i;
int y = rand() % 7 + 1;
 
int load1,j;
 
char s[2];
 
s[0] = 'T'; s[1] = 0;
 
for (;;) {
i = 1;
while (i < ASTER_LIM) {
load1 = 27000;
for (j=0; j<load1; j++) {
puts_xy(i,y,rand()%15+1,s);
}
//kern_cli();
//stat[n_stat].r_time = CBSGHD_get_response_time(5, exec_shadow);
//jet_gettable(exec_shadow, &stat[n_stat].ex_time, 1);
//kern_sti();
//n_stat++;
task_endcycle();
puts_xy(i,y,WHITE," ");
i++;
}
}
}
 
 
TASK clock()
{
int s = 0, m = 0;
 
while(1) {
printf_xy(62,1,WHITE,"%2d:%2d",m,s);
printf_xy(62,2,WHITE,"Utot=%12u",MAX_BANDWIDTH);
printf_xy(62,3,WHITE,"Uedf=%12u",EDF_usedbandwidth(0));
printf_xy(62,4,WHITE,"Ucbs=%12u",CBSGHD_usedbandwidth(1));
task_endcycle();
if (++s > 59) {
s = 0;
m++;
}
printf_xy(62,1,WHITE,"%2d:%2d",m,s);
printf_xy(62,2,WHITE,"Utot=%12u",MAX_BANDWIDTH);
printf_xy(62,3,WHITE,"Uedf=%12u",EDF_usedbandwidth(0));
printf_xy(62,4,WHITE,"Ucbs=%12u",CBSGHD_usedbandwidth(1));
task_endcycle();
}
}
 
 
 
/* we consider the first ASTER_MAX + 2 tasks from the PID 2
and plot on the screen the elapsed times... */
TASK jetcontrol()
{
int i; /* a counter */
TIME sum, max, curr, last[5];
int nact;
int j; /* the elements set by jet_gettable */
PID p;
 
 
kern_cli();
printf_xy(0,STAT_Y,WHITE,"PID ³ Mean T.³ Max T. ³ N.A. ³ Curr. ³ Last1 ³ Last2 ³ Last3 ³ Last4 ³ Last5");
kern_sti();
 
for (;;) {
for (i=0,p=0; i<DISPLAY_MAX+5 && p<MAX_PROC; p++) {
if (jet_getstat(p, &sum, &max, &nact, &curr) == -1) continue;
 
for (j=0; j<5; j++) last[j] = 0;
jet_gettable(p, &last[0], 5);
kern_cli();
printf_xy(0,STAT_Y+i+1,WHITE,"%-3d ³ %-6ld ³ %-6ld ³ %-4d ³ %-7ld ³ %-5ld ³ %-5ld ³ %-5ld ³ %-5ld ³ %-5ld", p, sum/(nact==0 ? 1 : nact), max,
nact, curr, last[0], last[1], last[2], last[3], last[4]);
kern_sti();
i++;
}
task_endcycle();
}
}
 
 
void save_stat(struct statistic p[], int n, char *name, int type)
{
DOS_FILE *f;
int i;
char outstring[500];
for(i = 0; i < 500; i++)
outstring[i] = '0';
f = DOS_fopen(name, "w");
if (!f) {
cprintf("Cannot open %s!!!", name);
goto end1;
}
for(i = 0; i < n; i++) {
if (type == RVAL)
val[i] = p[i].r_time;
if (type == XVAL)
val[i] = p[i].ex_time;
if (type == DVAL)
val[i] = p[i].dead_post;
}
memset(outstring, 0, 300);
sprintf(outstring, "%ld \n", (long int)n);
cprintf("%s", outstring);
DOS_fwrite(outstring, 1, strlen(outstring), f);
 
for(i = 0; i < n; i++) {
memset(outstring, 0, 300);
sprintf(outstring, "%ld %lu\n", (long int)i, val[i]);
//cprintf("%s", outstring);
DOS_fwrite(outstring, 1, strlen(outstring), f);
}
DOS_fclose(f);
end1:cprintf("OK?");
}
 
 
void result_save(void *p)
{
save_stat(stat, n_stat, "stat1.tim", RVAL);
}
 
 
void fine()
{
sys_end();
}
 
int main(int argc, char **argv)
{
PID p1,p2,p3, p4, p5, p6, p7;
 
ELASTIC_HARD_TASK_MODEL m;
// int i;
struct timespec fineprg;
 
 
//sys_atrunlevel(result_save, NULL, RUNLEVEL_AFTER_EXIT);
srand(7);
 
elastic_hard_task_default_model(m);
elastic_hard_task_def_wcet(m,500);
elastic_hard_task_def_maxperiod(m,500000);
elastic_hard_task_def_cnormal(m,500);
elastic_hard_task_def_period(m,500000);
elastic_hard_task_def_group(m,1);
elastic_hard_task_def_ctrl_jet(m);
 
 
p1 = task_create("Clock",clock,&m,NULL);
if (p1 == -1) {
perror("testhd.c(main): Could not create task <Clock> ...");
sys_end();
}
 
 
 
 
elastic_hard_task_def_wcet(m,1000);
elastic_hard_task_def_maxperiod(m,100000);
elastic_hard_task_def_cnormal(m,1000);
elastic_hard_task_def_period(m,100000);
p2 = task_create("JetControl",jetcontrol,&m,NULL);
if (p2 == -1) {
perror("testhd.c(main): Could not create task <JetControl> ...");
sys_end();
}
 
elastic_hard_task_def_wcet(m,21000);
elastic_hard_task_def_maxperiod(m,155000);
elastic_hard_task_def_cnormal(m,21000);
elastic_hard_task_def_period(m,155000);
 
 
p3 = task_create("Hard_asteroide1",hard_asteroide1,&m,NULL);
if (p3 == -1) {
perror("testhd.c(main): Could not create task <Hard asteroide> ...");
sys_end();
}
 
elastic_hard_task_def_wcet(m,12000);
elastic_hard_task_def_maxperiod(m,61000);
elastic_hard_task_def_cnormal(m,12000);
elastic_hard_task_def_period(m,61000);
 
 
 
p4 = task_create("Hard_asteroide2",hard_asteroide,&m,NULL);
if (p4 == -1) {
perror("testhd.c(main): Could not create task <Hard asteroide> ...");
sys_end();
}
 
 
elastic_hard_task_def_wcet(m,30000);
elastic_hard_task_def_maxperiod(m,200000);
elastic_hard_task_def_cnormal(m,30000);
elastic_hard_task_def_period(m,200000);
 
 
p5 = task_create("Hard_asteroide3",hard_asteroide2,&m,NULL);
if (p5 == -1) {
perror("testhd.c(main): Could not create task <Hard asteroide> ...");
sys_end();
}
 
elastic_hard_task_def_wcet(m,30000);
elastic_hard_task_def_maxperiod(m,100000);
elastic_hard_task_def_cnormal(m,30000);
elastic_hard_task_def_period(m,100000);
 
 
p6 = task_create("Hard_asteroide3",hard_asteroide2,&m,NULL);
if (p6 == -1) {
perror("testhd.c(main): Could not create task <Hard asteroide> ...");
sys_end();
}
elastic_hard_task_def_wcet(m,10000);
elastic_hard_task_def_maxperiod(m,200000);
elastic_hard_task_def_cnormal(m,2500);
elastic_hard_task_def_period(m,49000);
 
 
p7 = task_create("Hard_asteroide3",hard_asteroide3,&m,NULL);
if (p7 == -1) {
perror("testhd.c(main): Could not create task <Hard asteroide> ...");
sys_end();
}
 
 
 
printf_xy(0,STAT_Y + 15,WHITE,"Hard asteroide PID= %-3d ",p3);
printf_xy(0,STAT_Y + 17,WHITE,"Clock PID= %-3d ",p1);
printf_xy(0,STAT_Y + 18,WHITE,"JetControl PID= %-3d ",p2);
 
task_nopreempt();
fineprg.tv_sec = 30;
fineprg.tv_nsec = 0;
kern_event_post(&fineprg,fine,NULL);
group_activate(1);
return 0;
}
 
/advdemos/branches/advdemos/cash/cash.c
0,0 → 1,814
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: cash.c,v 1.1.1.1 2004-05-24 17:54:49 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:49 $
------------
 
This file contains the aperiodic server CBS (Total Bandwidth Server)
 
Read CBS.h for further details.
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#include "cash.h"
#include <ll/stdio.h>
#include <ll/string.h>
#include <kernel/model.h>
#include <kernel/descr.h>
#include <kernel/var.h>
#include <kernel/func.h>
 
/*+ Status used in the level +*/
#define CBSGHD_IDLE APER_STATUS_BASE /*+ waiting the activation +*/
#define CBSGHD_ZOMBIE APER_STATUS_BASE+1 /*+ waiting the period end +*/
 
/* structure of an element of the capacity queue */
struct cap_queue {
int cap;
struct timespec dead;
struct cap_queue *next;
};
 
/*+ the level redefinition for the CBS_HD level +*/
typedef struct {
level_des l; /*+ the standard level descriptor +*/
 
/* The wcet are stored in the task descriptor, but we need
an array for the deadlines. We can't use the timespec_priority
field because it is used by the master level!!!...
Notice that however the use of the timespec_priority field
does not cause any problem... */
 
struct timespec cbsghd_dline[MAX_PROC]; /*+ CBSGHD deadlines +*/
TIME period[MAX_PROC]; /*+ CBSGHD activation period +*/
 
TIME maxperiod[MAX_PROC]; /*+ maximum period of each elastic task +*/
int cremaining[MAX_PROC]; /*+ instance remaining computation time +*/
 
TIME act_period[MAX_PROC]; /*+ actual period of each elastic task: it
must be less than maxperiod!!! +*/
 
struct timespec request_time[MAX_PROC]; /* used for the response time */
TIME last_response_time[MAX_PROC]; /* response time of the last instance */
TIME cnormal[MAX_PROC]; /*+ CBSGHD normal computation time +*/
 
struct timespec reactivation_time[MAX_PROC];
/*+ the time at witch the reactivation timer is post +*/
int reactivation_timer[MAX_PROC];
/*+ the recativation timer +*/
 
struct cap_queue *queue; /* pointer to the spare capacity queue */
 
int flags; /*+ the init flags... +*/
 
bandwidth_t U; /*+ the used bandwidth by the server +*/
 
int idle; /* the idle flag... */
struct timespec start_idle; /*gives the start time of the last idle period */
LEVEL scheduling_level;
 
} CBSGHD_level_des;
 
 
/* insert a capacity in the queue capacity ordering by deadline */
 
static int c_insert(struct timespec dead, int cap, struct cap_queue **que,
PID p)
{
struct cap_queue *prev, *n, *new;
 
prev = NULL;
n = *que;
 
while ((n != NULL) &&
!TIMESPEC_A_LT_B(&dead, &n->dead)) {
prev = n;
n = n->next;
}
 
new = (struct cap_queue *)kern_alloc(sizeof(struct cap_queue));
if (new == NULL) {
kern_printf("\nNew cash_queue element failed\n");
kern_raise(XINVALID_TASK, p);
return -1;
}
new->next = NULL;
new->cap = cap;
new->dead = dead;
if (prev != NULL)
prev->next = new;
else
*que = new;
 
if (n != NULL)
new->next = n;
return 0;
}
 
/* extract the first element from the capacity queue */
 
static int c_extractfirst(struct cap_queue **que)
{
struct cap_queue *p = *que;
 
 
if (*que == NULL) return(-1);
*que = (*que)->next;
kern_free(p, sizeof(struct cap_queue));
return(1);
}
 
/* read data of the first element from the capacity queue */
 
static void c_readfirst(struct timespec *d, int *c, struct cap_queue *que)
{
*d = que->dead;
*c = que->cap;
}
 
/* write data of the first element from the capacity queue */
 
static void c_writefirst(struct timespec dead, int cap, struct cap_queue *que)
{
que->dead = dead;
que->cap = cap;
}
 
 
static void CBSGHD_activation(CBSGHD_level_des *lev,
PID p,
struct timespec *acttime)
{
JOB_TASK_MODEL job;
/* This rule is used when we recharge the budget at initial task activation
and each time a new task instance must be activated */
if (TIMESPEC_A_GT_B(acttime, &lev->cbsghd_dline[p])) {
/* we modify the deadline ... */
TIMESPEC_ASSIGN(&lev->cbsghd_dline[p], acttime);
}
 
lev->act_period[p] = 0;
if (proc_table[p].avail_time > 0)
proc_table[p].avail_time = 0;
 
 
 
 
/* there is a while because if the wcet is << than the system tick
we need to postpone the deadline many times */
while (proc_table[p].avail_time <= 0) {
/* A spare capacity is inserted in the capacity queue!! */
ADDUSEC2TIMESPEC(lev->period[p], &lev->cbsghd_dline[p]);
lev->act_period[p] += lev->period[p];
c_insert(lev->cbsghd_dline[p], lev->cnormal[p], &lev->queue, p);
/* it exploits available capacities from the capacity queue */
while (proc_table[p].avail_time < (int)lev->cnormal[p] &&
lev->queue != NULL) {
struct timespec dead;
int cap, delta;
delta = lev->cnormal[p] - proc_table[p].avail_time;
c_readfirst(&dead, &cap, lev->queue);
if (!TIMESPEC_A_GT_B(&dead, &lev->cbsghd_dline[p])) {
if (cap > delta) {
proc_table[p].avail_time += delta;
c_writefirst(dead, cap - delta, lev->queue);
}
else {
proc_table[p].avail_time += cap;
c_extractfirst(&lev->queue);
}
}
else
break;
}
}
lev->cremaining[p] = proc_table[p].wcet - proc_table[p].avail_time;
 
#ifdef TESTG
if (starttime && p == 3) {
oldx = x;
x = ((lev->cbsghd_dline[p].tv_sec*1000000+lev->cbsghd_dline[p].tv_nsec/1000)/5000 - starttime) + 20;
// kern_printf("(a%d)",lev->cbsghd_dline[p].tv_sec*1000000+lev->cbsghd_dline[p].tv_nsec/1000);
if (oldx > x) sys_end();
if (x<640)
grx_plot(x, 15, 8);
}
#endif
 
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, lev->cbsghd_dline[p]);
job_task_def_yesexc(job);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
}
 
 
/* this is the periodic reactivation of the task... */
static void CBSGHD_timer_reactivate(void *par)
{
PID p = (PID) par;
CBSGHD_level_des *lev;
 
lev = (CBSGHD_level_des *)level_table[proc_table[p].task_level];
 
if (proc_table[p].status == CBSGHD_IDLE) {
/* the task has finished the current activation and must be
reactivated */
/* request_time represents the time of the last instance release!! */
TIMESPEC_ASSIGN(&lev->request_time[p], &lev->reactivation_time[p]);
/* If idle=1, then we have to discharge the capacities stored in
the capacity queue up to the length of the idle interval */
if (lev->idle == 1) {
TIME interval;
struct timespec delta;
lev->idle = 0;
SUBTIMESPEC(&lev->request_time[p], &lev->start_idle, &delta);
/* length of the idle interval expressed in usec! */
interval = TIMESPEC2NANOSEC(&delta) / 1000;
 
/* it discharge the available capacities from the capacity queue */
while (interval > 0 && lev->queue != NULL) {
struct timespec dead;
int cap;
c_readfirst(&dead, &cap, lev->queue);
if (cap > interval) {
c_writefirst(dead, cap - interval, lev->queue);
interval = 0;
}
else {
interval -= cap;
c_extractfirst(&lev->queue);
}
}
}
 
CBSGHD_activation(lev,p,&lev->reactivation_time[p]);
 
/* check the constraint on the maximum period permitted... */
if (lev->act_period[p] > lev->maxperiod[p]) {
kern_printf("Deadline miss(timer_react.! process:%d act_period:%lu maxperiod:%lu\n",
p, lev->act_period[p], lev->maxperiod[p]);
kern_raise(XDEADLINE_MISS,p);
}
 
/* Set the reactivation timer */
TIMESPEC_ASSIGN(&lev->reactivation_time[p], &lev->cbsghd_dline[p]);
lev->reactivation_timer[p] = kern_event_post(&lev->reactivation_time[p],
CBSGHD_timer_reactivate,
(void *)p);
event_need_reschedule();
}
else {
/* this situation cannot occur */
kern_printf("Trying to reactivate a task which is not IDLE!!!/n");
kern_raise(XINVALID_TASK,p);
}
}
 
 
 
 
 
static void CBSGHD_avail_time_check(CBSGHD_level_des *lev, PID p)
{
/*+ if the capacity became negative the remaining computation time
is diminuished.... +*/
/* if (p==4)
kern_printf("(old dead:%d av_time:%d crem:%d)\n",
lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000, proc_table[p].avail_time,
lev->cremaining[p]); */
 
if (proc_table[p].avail_time < 0)
lev->cremaining[p] += proc_table[p].avail_time;
if (lev->cremaining[p] <= 0) {
kern_printf("Task:%d WCET violation \n", p);
kern_raise(XWCET_VIOLATION, p);
ll_abort(666);
}
 
/* there is a while because if the wcet is << than the system tick
we need to postpone the deadline many times */
while (proc_table[p].avail_time <= 0) {
/* it exploits available capacities from the capacity queue */
while (proc_table[p].avail_time < lev->cremaining[p]
&& lev->queue != NULL) {
struct timespec dead;
int cap, delta;
delta = lev->cremaining[p] - proc_table[p].avail_time;
c_readfirst(&dead, &cap, lev->queue);
if (!TIMESPEC_A_GT_B(&dead, &lev->cbsghd_dline[p])) {
if (cap > delta) {
proc_table[p].avail_time += delta;
c_writefirst(dead, cap - delta, lev->queue);
}
else {
proc_table[p].avail_time += cap;
c_extractfirst(&lev->queue);
}
}
else
break;
}
 
/* if (p==5 && proc_table[p].avail_time <= 0 &&
lev->cremaining[p] > lev->cnormal[p])
kern_printf("(inter dead:%d av_time:%d crem:%d)\n",
lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000, proc_table[p].avail_time,
lev->cremaining[p]); */
/* The remaining computation time is modified according
to the new budget! */
if (proc_table[p].avail_time > 0)
lev->cremaining[p] -= proc_table[p].avail_time;
else {
/* the CBSGHD rule for recharging the capacity: */
if (lev->cremaining[p] > lev->cnormal[p]) {
ADDUSEC2TIMESPEC(lev->period[p], &lev->cbsghd_dline[p]);
lev->act_period[p] += lev->period[p];
/* A spare capacity is inserted in the capacity queue!! */
c_insert(lev->cbsghd_dline[p], lev->cnormal[p], &lev->queue, p);
}
else {
TIME t;
t = (lev->cremaining[p] * lev->period[p]) / lev->cnormal[p];
ADDUSEC2TIMESPEC(t, &lev->cbsghd_dline[p]);
lev->act_period[p] += t;
/* A spare capacity is inserted in the capacity queue!! */
c_insert(lev->cbsghd_dline[p], lev->cremaining[p], &lev->queue, p);
}
}
}
/* if (p==4)
kern_printf("n dead:%d av_time:%d crem:%d)\n",
lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000, proc_table[p].avail_time,
lev->cremaining[p]); */
 
/* check the constraint on the maximum period permitted... */
if (lev->act_period[p] > lev->maxperiod[p]) {
/*kern_printf("n dead:%d av_time:%d crem:%d)\n",
lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000, proc_table[p].avail_time,
lev->cremaining[p]); */
kern_printf("Deadline miss(av.time_check! process:%d act_period:%lu maxperiod:%lu\n",
p, lev->act_period[p], lev->maxperiod[p]);
kern_raise(XDEADLINE_MISS,p);
}
 
 
if (TIMESPEC_A_LT_B(&lev->reactivation_time[p], &lev->cbsghd_dline[p])) {
/* we delete the reactivation timer */
kern_event_delete(lev->reactivation_timer[p]);
/* repost the event at the next instance deadline... */
lev->reactivation_time[p] = lev->cbsghd_dline[p];
lev->reactivation_timer[p] = kern_event_post(&lev->reactivation_time[p],
CBSGHD_timer_reactivate,
(void *)p);
}
#ifdef TESTG
if (starttime && p == 3) {
oldx = x;
x = ((lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000)/5000 - starttime) + 20;
// kern_printf("(e%d avail%d)",lev->cbsghd_dline[p].tv_sec*1000000+
lev->cbsghd_dline[p].tv_nsec/1000,proc_table[p].avail_time);
if (oldx > x) sys_end();
if (x<640)
grx_plot(x, 15, 2);
}
#endif
}
 
 
/*+ this function is called when a killed or ended task reach the
period end +*/
static void CBSGHD_timer_zombie(void *par)
{
PID p = (PID) par;
CBSGHD_level_des *lev;
 
lev = (CBSGHD_level_des *)level_table[proc_table[p].task_level];
 
/* we finally put the task in the FREE status */
proc_table[p].status = FREE;
iq_insertfirst(p,&freedesc);
 
/* and free the allocated bandwidth */
lev->U -= (MAX_BANDWIDTH/lev->period[p]) * lev->cnormal[p];
 
}
 
static PID CBSGHD_public_scheduler(LEVEL l)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
/* it stores the actual time and set the IDLE flag in order to handle
the capacity queue discharging!!! */
lev->idle = 1;
kern_gettime(&lev->start_idle);
 
/* the CBSGHD don't schedule anything...
it's an EDF level or similar that do it! */
return NIL;
}
 
/* The on-line guarantee is enabled only if the appropriate flag is set... */
static int CBSGHD_public_guarantee(LEVEL l, bandwidth_t *freebandwidth)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
if (lev->flags & CBSGHD_FAILED_GUARANTEE) {
*freebandwidth = 0;
//kern_printf("guarantee :garanzia fallita!!!!!!\n");
return 0;
}
else if (*freebandwidth >= lev->U) {
*freebandwidth -= lev->U;
return 1;
}
else {
//kern_printf("guarantee :garanzia fallita per mancanza di banda!!!!!!\n");
//kern_printf("freeband: %d request band: %d", *freebandwidth, lev->U);
return 0;
}
}
 
static int CBSGHD_public_create(LEVEL l, PID p, TASK_MODEL *m)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
ELASTIC_HARD_TASK_MODEL *s;
bandwidth_t b1, b2;
 
if (m->pclass != ELASTIC_HARD_PCLASS) return -1;
if (m->level != 0 && m->level != l) return -1;
s = (ELASTIC_HARD_TASK_MODEL *)m;
 
/* kern_printf("accept :ELASTIC TASK found!!!!!!\n"); */
b1 = (MAX_BANDWIDTH / s->period) * s->cnormal;
b2 = (MAX_BANDWIDTH / s->maxperiod) * s->wcet;
if (!(s->wcet && s->cnormal && s->period && s->maxperiod &&
s->wcet >= s->cnormal && b1 >= b2) )
return -1;
/* kern_printf("period: %d maxperiod: %d cnormal: %d wcet: %d, b1: %d b2:
%d\n", s->period, s->maxperiod, s->cnormal, s->wcet, b1, b2); */
 
/* now we know that m is a valid model */
 
 
/* Enable wcet check */
proc_table[p].avail_time = 0;
proc_table[p].wcet = s->wcet;
proc_table[p].control |= CONTROL_CAP;
 
lev->period[p] = s->period;
lev->maxperiod[p] = s->maxperiod;
lev->cnormal[p] = s->cnormal;
NULL_TIMESPEC(&lev->cbsghd_dline[p]);
NULL_TIMESPEC(&lev->request_time[p]);
 
 
/* update the bandwidth... */
if (lev->flags & CBSGHD_ENABLE_GUARANTEE) {
bandwidth_t b;
b = (MAX_BANDWIDTH / s->period) * s->cnormal;
 
/* really update lev->U, checking an overflow... */
if (MAX_BANDWIDTH - lev->U > b)
lev->U += b;
else
/* The task can NOT be guaranteed (U>MAX_BANDWIDTH)...
(see EDF.c) */
lev->flags |= CBSGHD_FAILED_GUARANTEE;
}
 
 
return 0; /* OK, also if the task cannot be guaranteed... */
}
 
static void CBSGHD_public_detach(LEVEL l, PID p)
{
/* the CBSGHD level doesn't introduce any dinamic allocated new field.
we have only to reset the NO_GUARANTEE FIELD and decrement the allocated
bandwidth */
 
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
if (lev->flags & CBSGHD_FAILED_GUARANTEE)
lev->flags &= ~CBSGHD_FAILED_GUARANTEE;
else
lev->U -= (MAX_BANDWIDTH / lev->period[p]) * lev->cnormal[p];
 
}
 
static void CBSGHD_public_dispatch(LEVEL l, PID p, int nostop)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
level_table[ lev->scheduling_level ]->
private_dispatch(lev->scheduling_level,p,nostop);
 
}
 
static void CBSGHD_public_epilogue(LEVEL l, PID p)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
JOB_TASK_MODEL job;
 
/* check if the budget is finished... */
if ( proc_table[p].avail_time <= 0) {
/* we kill the current activation */
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level, p);
 
/* we modify the deadline */
CBSGHD_avail_time_check(lev, p);
 
/* and, finally, we reinsert the task in the master level */
job_task_default_model(job, lev->cbsghd_dline[p]);
job_task_def_yesexc(job);
level_table[ lev->scheduling_level ]->
private_insert(lev->scheduling_level, p, (TASK_MODEL *)&job);
// kern_printf("epil : dl %d per %d p %d |\n",
// lev->cbsghd_dline[p].tv_nsec/1000,lev->period[p],p);
 
}
else
/* the task has been preempted. it returns into the ready queue by
calling the guest_epilogue... */
level_table[ lev->scheduling_level ]->
private_epilogue(lev->scheduling_level,p);
}
 
static void CBSGHD_public_activate(LEVEL l, PID p)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
kern_gettime(&lev->request_time[p]);
/* If idle=1, then we have to discharge the capacities stored in
the capacity queue up to the length of the idle interval */
if (lev->idle == 1) {
TIME interval;
struct timespec delta;
lev->idle = 0;
SUBTIMESPEC(&lev->request_time[p], &lev->start_idle, &delta);
/* length of the idle interval expressed in usec! */
interval = TIMESPEC2NANOSEC(&delta) / 1000;
 
/* it discharge the available capacities from the capacity queue */
while (interval > 0 && lev->queue != NULL) {
struct timespec dead;
int cap;
c_readfirst(&dead, &cap, lev->queue);
if (cap > interval) {
c_writefirst(dead, cap - interval, lev->queue);
interval = 0;
}
else {
interval -= cap;
c_extractfirst(&lev->queue);
}
}
}
CBSGHD_activation(lev, p, &lev->request_time[p]);
 
 
/* check the constraint on the maximum period permitted... */
if (lev->act_period[p] > lev->maxperiod[p]) {
kern_printf("Deadline miss(task_activ.! process:%d act_period:%lu maxperiod:%lu\n",
p, lev->act_period[p], lev->maxperiod[p]);
kern_raise(XDEADLINE_MISS,p);
}
/* Set the reactivation timer */
TIMESPEC_ASSIGN(&lev->reactivation_time[p], &lev->cbsghd_dline[p]);
lev->reactivation_timer[p] = kern_event_post(&lev->reactivation_time[p],
CBSGHD_timer_reactivate,
(void *)p);
// kern_printf("act : %d %d |",lev->cbsghd_dline[p].tv_nsec/1000,p);
}
 
static void CBSGHD_public_unblock(LEVEL l, PID p)
{
printk("CBSGHD_task_insert\n");
kern_raise(XINVALID_TASK,p);
}
 
static void CBSGHD_public_block(LEVEL l, PID p)
{
printk("CBSGHD_task_extract\n");
kern_raise(XINVALID_TASK,p);
}
 
static int CBSGHD_public_message(LEVEL l, PID p, void *m)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
struct timespec act_time, res;
 
/* It computes the response time of the current instance... */
kern_gettime(&act_time);
SUBTIMESPEC(&act_time, &lev->request_time[p], &res);
/* response time expressed in usec! */
lev->last_response_time[p] = TIMESPEC2NANOSEC(&res) / 1000;
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p);
 
/* A spare capacity is inserted in the capacity queue!! */
if (proc_table[p].avail_time > 0) {
c_insert(lev->cbsghd_dline[p], proc_table[p].avail_time, &lev->queue, p);
proc_table[p].avail_time = 0;
}
 
proc_table[p].status = CBSGHD_IDLE;
 
jet_update_endcycle(); /* Update the Jet data... */
 
return 0;
}
 
static void CBSGHD_public_end(LEVEL l, PID p)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
/* check if the capacity became negative... */
/* there is a while because if the wcet is << than the system tick
we need to postpone the deadline many times */
while (proc_table[p].avail_time < 0) {
/* the CBSGHD rule for recharging the capacity */
proc_table[p].avail_time += lev->cnormal[p];
ADDUSEC2TIMESPEC(lev->period[p], &lev->cbsghd_dline[p]);
}
level_table[ lev->scheduling_level ]->
private_extract(lev->scheduling_level,p);
 
/* we delete the reactivation timer */
kern_event_delete(lev->reactivation_timer[p]);
lev->reactivation_timer[p] = -1;
 
/* Finally, we post the zombie event. when the end period is reached,
the task descriptor and banwidth are freed */
proc_table[p].status = CBSGHD_ZOMBIE;
lev->reactivation_timer[p] = kern_event_post(&lev->cbsghd_dline[p],
CBSGHD_timer_zombie,
(void *)p);
}
 
/* Registration functions */
 
/*+ Registration function:
int flags the init flags ... see CBS.h +*/
LEVEL CBSGHD_register_level(int flags, LEVEL master)
{
LEVEL l; /* the level that we register */
CBSGHD_level_des *lev; /* for readableness only */
PID i; /* a counter */
 
printk("CBSGHD_register_level\n");
 
/* request an entry in the level_table */
l = level_alloc_descriptor(sizeof(CBSGHD_level_des));
 
lev = (CBSGHD_level_des *)level_table[l];
 
printk(" lev=%d\n",(int)lev);
 
/* fill the standard descriptor */
lev->l.public_scheduler = CBSGHD_public_scheduler;
 
if (flags & CBSGHD_ENABLE_GUARANTEE)
lev->l.public_guarantee = CBSGHD_public_guarantee;
else
lev->l.public_guarantee = NULL;
 
lev->l.public_create = CBSGHD_public_create;
lev->l.public_detach = CBSGHD_public_detach;
lev->l.public_end = CBSGHD_public_end;
lev->l.public_dispatch = CBSGHD_public_dispatch;
lev->l.public_epilogue = CBSGHD_public_epilogue;
lev->l.public_activate = CBSGHD_public_activate;
lev->l.public_unblock = CBSGHD_public_unblock;
lev->l.public_block = CBSGHD_public_block;
lev->l.public_message = CBSGHD_public_message;
 
/* fill the CBSGHD descriptor part */
for (i=0; i<MAX_PROC; i++) {
NULL_TIMESPEC(&lev->cbsghd_dline[i]);
lev->period[i] = 0;
NULL_TIMESPEC(&lev->request_time[i]);
lev->last_response_time[i] = 0;
NULL_TIMESPEC(&lev->reactivation_time[i]);
lev->reactivation_timer[i] = -1;
}
 
 
lev->U = 0;
lev->idle = 0;
lev->queue = NULL;
lev->scheduling_level = master;
 
lev->flags = flags & 0x07;
 
return l;
}
 
 
int CBSGHD_get_response_time(LEVEL l, PID p)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
return lev->last_response_time[p];
}
 
 
bandwidth_t CBSGHD_usedbandwidth(LEVEL l)
{
CBSGHD_level_des *lev = (CBSGHD_level_des *)(level_table[l]);
 
return lev->U;
}
 
/advdemos/branches/advdemos/cash/initcash.c
0,0 → 1,128
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: initcash.c,v 1.1.1.1 2004-05-24 17:54:49 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:49 $
------------
 
System initialization file
 
The tick is set to TICK ms.
 
This file contains the 2 functions needed to initialize the system.
 
These functions register the following levels:
 
an EDF (Earliest Deadline First) level
a RR (Round Robin) level
a CBSHD (Constant Bandwidth Server with Hard Deadlines) level
a Dummy level
 
 
 
It can accept these task models (into () the mandatory fields):
 
HARD_TASK_MODEL (wcet+mit) at level 0
NRT_TASK_MODEL at level 1
ELASTIC_HARD_TASK_MODEL (cnormal,period,wcet,maxperiod) at level 5
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/rr.h"
#include "modules/tbs.h"
#include "modules/cbs.h"
#include "cash.h"
#include "modules/dummy.h"
#include "modules/sem.h"
#include "modules/hartport.h"
#include "drivers/keyb.h"
 
 
/*+ sysyem tick in us +*/
#define TICK 300
 
#define RRTICK 5000
 
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDF_register_level(EDF_ENABLE_ALL);
CBSGHD_register_level(CBSGHD_ENABLE_ALL, 0);
RR_register_level(RRTICK, RR_MAIN_YES, mb);
/* CBS_register_level(CBS_ENABLE_ALL, 0); */
//CBSHD_register_level(CBSHD_ENABLE_ALL, 0);
dummy_register_level();
 
SEM_register_module();
 
return TICK;
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
HARTPORT_init();
 
KEYB_init(NULL);
 
__call_main__(mb);
 
return (void *)0;
}
 
 
 
 
 
 
 
 
 
 
/advdemos/branches/advdemos/cash/cash.h
0,0 → 1,177
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/**
------------
CVS : $Id: cash.h,v 1.1.1.1 2004-05-24 17:54:50 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:50 $
------------
 
This file contains the server CBSHD (CASH Algorithm)
 
Title:
CBSHD (Constant Bandwidth Server with hard deadlines)
 
Task Models Accepted:
ELASTIC_HARD_TASK_MODEL - Elastic Hard Tasks
wcet field must be != 0
cnormal field must be != 0
period field must be != 0
Description:
This module schedule his tasks following the CBSHD scheme.
(see Marco Caccamo, Giorgio Buttazzo and Lui Sha
"Elastic Feedback Control"
Proceedings of the EUROMICRO 2000)
 
The tasks are inserted in an EDF level (or similar) with a JOB_TASK_MODEL,
and the CBSHD level expects that the task is scheduled with the absolute
deadline passed in the model.
 
The task guarantee is based on the factor utilization approach.
 
Exceptions raised:
XUNVALID_GUEST
This level doesn't support guests. When a guest operation
is called, the exception is raised.
 
These exceptions are pclass-dependent...
XDEADLINE_MISS
If a task miss his deadline, the exception is raised.
Restrictions & special features:
- This level doesn't manage the main task.
- At init time we have to specify:
. guarantee check
(when all task are created the system will check that the task_set
will not use more than the available bandwidth)
- A function to return the used bandwidth of the level is provided.
- A function to return the pending activations of the task.
 
**/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
 
#ifndef __CBSGHD_H__
#define __CBSGHD_H__
 
#include <ll/ll.h>
#include <kernel/config.h>
#include <sys/types.h>
#include <kernel/types.h>
 
 
 
 
 
 
 
 
/*+ flags... +*/
#define CBSGHD_ENABLE_GUARANTEE 1 /*+ Task Guarantee enabled +*/
#define CBSGHD_ENABLE_ALL 1
 
#define CBSGHD_FAILED_GUARANTEE 8 /*+ used in the module, unsettabl
in EDF_register_level... +*/
 
 
 
 
 
#define ELASTIC_HARD_PCLASS 0x0600
 
#define CBSGHD_LEVELNAME "CBSGHD base"
#define CBSGHD_LEVEL_CODE 106
#define CBSGHD_LEVEL_VERSION 1
 
 
/* -----------------------------------------------------------------------
ELASTIC_HARD_TASK_MODEL: elastic hard Tasks
----------------------------------------------------------------------- */
 
typedef struct {
TASK_MODEL t;
TIME cnormal;
TIME period;
TIME wcet;
TIME maxperiod;
} ELASTIC_HARD_TASK_MODEL;
 
#define elastic_hard_task_default_model(m) \
task_default_model((m).t,ELASTIC_HARD_PCLASS), \
(m).cnormal = 0, \
(m).period = 0, \
(m).wcet = 0, \
(m).maxperiod = 0
#define elastic_hard_task_def_level(m,l) task_def_level((m).t,l)
#define elastic_hard_task_def_arg(m,a) task_def_arg((m).t,a)
#define elastic_hard_task_def_stack(m,s) task_def_stack((m).t,s)
#define elastic_hard_task_def_stackaddr(m,s) task_def_stackaddr((m).t,s)
#define elastic_hard_task_def_group(m,g) task_def_group((m).t,g)
#define elastic_hard_task_def_usemath(m) task_def_usemath((m).t)
#define elastic_hard_task_def_system(m) task_def_system((m).t)
#define elastic_hard_task_def_nokill(m) task_def_nokill((m).t)
#define elastic_hard_task_def_ctrl_jet(m) task_def_ctrl_jet((m).t)
#define elastic_hard_task_def_cnormal(m,c) (m).cnormal = (c)
#define elastic_hard_task_def_period(m,p) (m).period = (p)
#define elastic_hard_task_def_wcet(m,w) (m).wcet = (w)
#define elastic_hard_task_def_maxperiod(m,p) (m).maxperiod = (p)
#define elastic_hard_task_def_joinable(m) task_def_joinable((m).t)
#define elastic_hard_task_def_unjoinable(m) task_def_unjoinable((m).t)
 
 
 
 
/*+ Registration function:
int flags Options to be used in this level instance...
LEVEL master the level that must be used as master level for the
CBSGHD tasks
 
returns the level number at which the module has been registered.
+*/
LEVEL CBSGHD_register_level(int flags, LEVEL master);
 
/*+ Returns the used bandwidth of a level +*/
bandwidth_t CBSGHD_usedbandwidth(LEVEL l);
 
#endif
 
/advdemos/branches/advdemos/cash/readme.txt
0,0 → 1,6
This Example has been made by Marco Caccamo.
 
There is not a lot of documentation available, so if you have problems please
send an e-mail to Marco ( http://gandalf.sssup.it/~caccamo/ )
 
Paolo
/advdemos/branches/advdemos/cash/makefile
0,0 → 1,17
#
#
#
 
ifndef BASE
BASE=../..
endif
 
include $(BASE)/config/config.mk
 
PROGS=testcash
 
include $(BASE)/config/example.mk
 
testcash:
make -f $(SUBMAKE) APP=testcash INIT= OTHEROBJS="initcash.o cash.o" OTHERINCL= SHARKOPT="__OLDCHAR__ __GRX__"
 
/advdemos/branches/advdemos/fsf/test1.c
0,0 → 1,352
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
 
#include "modules/edf.h"
#include "modules/cbs.h"
 
#include "pthread.h"
#include "modules/posix.h"
 
#include "fsf_contract.h"
#include "fsf_server.h"
 
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/pi.h"
#include "modules/pc.h"
 
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
#include <stdlib.h>
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int grubstar_level;
 
EDF_register_level(EDF_ENABLE_ALL);
POSIX_register_level(RRTICK, 1, mb, 32);
grubstar_level = GRUBSTAR_register_level(4, 0);
FSF_register_module(grubstar_level, (int)(MAX_BANDWIDTH * 0.9));
dummy_register_level();
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
PI_register_module();
PC_register_module();
 
SEM_register_module();
 
PTHREAD_register_module(1, 0, 1);
 
return TICK;
}
 
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
HARTPORT_init();
 
KEYB_init(NULL);
__call_main__(mb);
 
return (void *)0;
 
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
pthread_t j1 = -1;
pthread_t j2 = -1;
pthread_t j3 = -1;
pthread_t j4 = -1;
fsf_server_id_t server1 = -1;
fsf_server_id_t server2 = -1;
fsf_server_id_t server3 = -1;
fsf_server_id_t server4 = -1;
fsf_contract_parameters_t contract1, contract2;
 
pthread_mutex_t mux;
 
#define TASK_PERIOD 1000000
 
void *periodic_star(void *arg)
{
struct timespec actual,end,next_time;
int actpersecond,act,cycle;
int mean,nmean;
bool was_deadline_missed, was_budget_overran;
 
act = 0;
actpersecond = 0;
mean = 0;
nmean = 0;
cycle = 0;
for (;;) {
kern_gettime(&actual);
cycle++;
 
if (act == 0) {
TIMESPEC_ASSIGN(&end,&actual);
end.tv_sec++;
}
 
if (TIMESPEC_A_LT_B(&actual,&end)) {
act++;
} else {
actpersecond = act;
act = 0;
mean = (mean * nmean + actpersecond) / (nmean+1);
nmean++;
}
 
//pthread_mutex_lock(&mux);
printf_xy(0,exec_shadow,WHITE,"Thread %3d Act_per_Second = %8d Mean = %8d Cycle = %8d",
exec_shadow,actpersecond,mean,cycle);
//pthread_mutex_unlock(&mux);
 
kern_gettime(&next_time);
ADDUSEC2TIMESPEC(TASK_PERIOD, &next_time);
fsf_schedule_next_timed_job(NULL, NULL, NULL, &was_deadline_missed, &was_budget_overran);
 
}
 
return NULL;
 
}
 
void *star(void *arg)
{
struct timespec actual,end;
int actpersecond,act;
int mean,nmean,cycle;
 
act = 0;
actpersecond = 0;
mean = 0;
nmean = 0;
cycle = 0;
for (;;) {
cycle++;
kern_gettime(&actual);
 
if (act == 0) {
TIMESPEC_ASSIGN(&end,&actual);
end.tv_sec++;
}
 
if (TIMESPEC_A_LT_B(&actual,&end)) {
act++;
} else {
actpersecond = act;
act = 0;
mean = (mean * nmean + actpersecond) / (nmean+1);
nmean++;
}
 
//pthread_mutex_lock(&mux);
printf_xy(0,exec_shadow,WHITE,"Thread %3d Act_per_Second = %8d Mean = %8d Cycle = %8d",
exec_shadow,actpersecond,mean,cycle);
//pthread_mutex_unlock(&mux);
 
}
 
return NULL;
 
}
 
void *edftask(void *arg)
{
int i,j;
while(1) {
for (i=0;i<5; i++) {
for (j=0; j<10; j++);
//cputc('#');
//cputs((char *)(arg));
}
 
task_endcycle();
}
 
return NULL;
}
 
 
void create()
{
HARD_TASK_MODEL mhard;
 
struct timespec period1 = {0,100000000};
struct timespec period2 = {0,100000000};
struct timespec budget1 = {0,30000000};
struct timespec budget2 = {0,30000000};
PID t1, t2;
 
kern_printf("(Start Create)");
 
hard_task_default_model(mhard);
hard_task_def_ctrl_jet(mhard);
hard_task_def_mit(mhard,32000);
hard_task_def_wcet(mhard,3000);
hard_task_def_arg(mhard,(void *)"X");
hard_task_def_group(mhard,1);
hard_task_def_periodic(mhard);
t1 = task_create("X", edftask, &mhard, NULL);
if (t1 == NIL) {
perror("Could not create task X ...");
sys_end();
}
 
hard_task_def_mit(mhard,32000);
hard_task_def_wcet(mhard,3000);
hard_task_def_arg(mhard,(void *)"Y");
t2 = task_create("Y", edftask, &mhard, NULL);
if (t2 == NIL) {
perror("Could not create task Y ...");
sys_end();
}
 
group_activate(1);
 
fsf_initialize_contract(&contract1);
fsf_set_contract_basic_parameters(&contract1,&budget1,&period1,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_initialize_contract(&contract2);
fsf_set_contract_basic_parameters(&contract2,&budget2,&period2,NULL,NULL,FSF_DEFAULT_WORKLOAD);
 
kern_printf("(End Create)");
 
}
 
int main(int argc, char **argv)
{
NRT_TASK_MODEL nrt;
char ch = 0;
int err;
 
pthread_mutex_init(&mux,NULL);
 
create();
 
nrt_task_default_model(nrt);
nrt_task_def_save_arrivals(nrt);
nrt_task_def_ctrl_jet(nrt);
 
do {
ch = keyb_getch(BLOCK);
 
switch(ch) {
case '1':
err = fsf_create_thread(server1,&j1,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
break;
case '2':
err = fsf_create_thread(server2,&j2,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
break;
case '3':
err = fsf_create_thread(server1,&j3,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
break;
case '4':
err = fsf_create_thread(server2,&j4,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
break;
case 'q':
err = fsf_negotiate_contract(&contract1,&server1);
cprintf("(%d)",err);
break;
case 'w':
err = fsf_negotiate_contract(&contract2,&server2);
kern_printf("(%d)",err);
break;
case 'e':
err = fsf_negotiate_contract(&contract1,&server3);
kern_printf("(%d)",err);
break;
case 'r':
err = fsf_cancel_contract(&server1);
kern_printf("(%d)",err);
break;
case 't':
err = fsf_cancel_contract(&server2);
kern_printf("(%d)",err);
break;
case 'y':
err = fsf_cancel_contract(&server3);
kern_printf("(%d)",err);
break;
 
}
 
} while(ch != ESC);
 
sys_end();
 
return 0;
 
}
 
/advdemos/branches/advdemos/fsf/test2.c
0,0 → 1,302
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*/
 
#include "kernel/kern.h"
 
#include "fsf_contract.h"
 
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
 
#include "pthread.h"
 
#include "drivers/keyb.h"
#include "drivers/glib.h"
 
#define TEST_PERIOD 50000
 
mutex_t mux;
 
void program_key_end(KEY_EVT *k)
{
 
sys_end();
 
}
 
void print_timer(int x, int y)
{
 
long nsec,sec,min,hrs,day;
struct timespec actual_timer;
char tmp[100];
 
sys_gettime(&actual_timer);
 
nsec = actual_timer.tv_nsec;
sec = actual_timer.tv_sec;
min = sec / 60;
sec %= 60;
hrs = min / 60;
min %= 60;
day = hrs / 24;
hrs %= 24;
 
sprintf(tmp,"Time: %2ld d %2ld h %2ld m %2ld s %12ld ns",day,hrs,min,sec,(long)nsec);
//mutex_lock(&mux);
grx_text(tmp,x,y,rgb16(255,255,255),0);
//mutex_unlock(&mux);
 
}
 
#define LOAD_VARIATION 10
 
#define MAX_V_QOS 30
#define MIN_V_QOS 2
 
void *test_task_variable(void *arg) {
 
char tmp[100];
long long i;
int task_qos;
int var_load, rd_per;
 
TIME exectime;
 
task_qos = 7;
var_load = 5;
rd_per = 0;
while(1) {
 
print_timer(307,10+30*exec_shadow);
sprintf(tmp,"Test Thread V QOS = %5d PID = %3d VLOAD = %3d",task_qos,exec_shadow,var_load);
//mutex_lock(&mux);
grx_text(tmp,307,20+30*exec_shadow,rgb16(255,255,255),0);
//mutex_unlock(&mux);
 
jet_gettable(exec_shadow, &exectime, 1);
sprintf(tmp,"Thread Exec Timer = %10d us",(int)exectime);
grx_text(tmp,307,30+30*exec_shadow,rgb16(255,255,255),0);
 
if (rd_per > LOAD_VARIATION) {
var_load += rand()%3-1;
if (var_load > 20) var_load = 20;
if (var_load < 0) var_load = 0;
rd_per = 0;
} else {
rd_per++;
}
for(i = 0; i < 10000*(task_qos+var_load); i++);
}
 
return NULL;
 
}
 
#define MAX_C_QOS 30
#define MIN_C_QOS 2
 
void *test_task_constant(void *arg) {
 
char tmp[100];
long long i;
int task_qos;
 
task_qos = 7;
while(1) {
 
print_timer(307,10+20*exec_shadow);
sprintf(tmp,"Test Task C QOS = %5d PID = %3d",task_qos,exec_shadow);
//mutex_lock(&mux);
grx_text(tmp,307,20+20*exec_shadow,rgb16(255,255,255),0);
//mutex_unlock(&mux);
for(i = 0; i < 10000*task_qos; i++);
}
 
return NULL;
 
}
 
void draw_box(int x1, int y1, int x2, int y2)
{
 
grx_rect(x1,y1,x2,y2,rgb16(160,160,160));
grx_rect(x1+2,y1+2,x2-2,y2-2,rgb16(210,210,210));
 
}
 
void layout_screen()
{
 
draw_box(0,0,300,500);
grx_text("Application Task List",5,5,rgb16(255,255,255),0);
draw_box(303,0,799,500);
grx_text("Task Output",305,5,rgb16(255,255,255),0);
draw_box(0,503,799,599);
grx_line(140,505,140,597,rgb16(255,255,255));
grx_line(140,583,797,583,rgb16(255,255,255));
grx_text("Application Statistics",142,507,rgb16(255,255,255),0);
}
 
void program_end()
{
 
grx_close();
}
 
void *mpeg2decoder(void *arg);
 
void add_posixstar_thread(fsf_server_id_t server)
{
NRT_TASK_MODEL nrt;
pthread_t j = -1;
nrt_task_default_model(nrt);
fsf_create_thread(server, &j, NULL, test_task_variable, NULL, &nrt);
 
}
 
void add_edfstar_thread(fsf_server_id_t server)
{
 
pthread_t j = -1;
HARD_TASK_MODEL ht;
 
hard_task_default_model(ht);
hard_task_def_mit(ht,100000);
hard_task_def_wcet(ht,90000);
fsf_create_thread(server, &j, NULL, mpeg2decoder, NULL, &ht);
 
}
 
int main(int argc, char **argv)
{
char ch;
int err;
KEY_EVT k;
PI_mutexattr_t a;
 
struct timespec period1 = {0,10000000};
struct timespec period2 = {0,10000000};
struct timespec budget1 = {0,4000000};
struct timespec budget2 = {0,4000000};
 
fsf_server_id_t server1, server2;
fsf_contract_parameters_t contract1, contract2;
 
sys_atrunlevel(program_end, NULL, RUNLEVEL_BEFORE_EXIT);
k.flag = ALTL_BIT;
k.scan = KEY_C;
k.ascii = 'c';
keyb_hook(k,program_key_end);
srand(sys_gettime(NULL));
 
// graphic card Initialization
if (grx_init() < 1) {
sys_end();
}
if (grx_open(800, 600, 16) < 0) {
cprintf("GRX Err\n");
sys_end();
}
 
layout_screen();
PI_mutexattr_default(a);
mutex_init(&mux,&a);
 
fsf_initialize_contract(&contract1);
fsf_set_contract_basic_parameters(&contract1,&budget1,&period1,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_initialize_contract(&contract2);
fsf_set_contract_basic_parameters(&contract2,&budget2,&period2,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_set_local_scheduler_parameter(&contract2, FSF_SCHEDULER_EDF);
err = fsf_negotiate_contract(&contract1,&server1);
if (err) cprintf("(FSF ERROR %d)",err);
err = fsf_negotiate_contract(&contract2,&server2);
if (err) cprintf("(FSF ERROR %d)",err);
ch = keyb_getch(BLOCK);
while(ch != ESC) {
 
switch (ch) {
 
case '1':
add_posixstar_thread(server1);
break;
case '2':
add_edfstar_thread(server2);
break;
case '3':
break;
case '4':
break;
case '5':
break;
}
 
ch = keyb_getch(BLOCK);
}
 
sys_end();
return 0;
 
}
/advdemos/branches/advdemos/fsf/test3.c
0,0 → 1,379
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2002 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
 
#include "modules/edf.h"
#include "modules/cbs.h"
 
#include "pthread.h"
#include "modules/posix.h"
 
#include "fsf_contract.h"
#include "fsf_server.h"
 
#include "modules/dummy.h"
 
#include "modules/sem.h"
#include "modules/pi.h"
#include "modules/pc.h"
 
#include "modules/hartport.h"
#include "modules/cabs.h"
 
#include "drivers/keyb.h"
#include <stdlib.h>
 
// --------------------------------------------------
// --------------------------------------------------
// Init Part
// --------------------------------------------------
// --------------------------------------------------
 
/*+ sysyem tick in us +*/
#define TICK 0
 
/*+ RR tick in us +*/
#define RRTICK 10000
 
int grubstar_level;
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
EDF_register_level(EDF_ENABLE_ALL);
POSIX_register_level(RRTICK, 1, mb, 32);
grubstar_level = GRUBSTAR_register_level(5, 0);
FSF_register_module(grubstar_level, (int)(MAX_BANDWIDTH * 0.9));
dummy_register_level();
 
// for the keyboard...
CBS_register_level(CBS_ENABLE_ALL, 0);
 
PI_register_module();
PC_register_module();
 
SEM_register_module();
 
PTHREAD_register_module(1, 0, 1);
 
return TICK;
}
 
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
HARTPORT_init();
 
KEYB_init(NULL);
__call_main__(mb);
 
return (void *)0;
 
}
 
// --------------------------------------------------
// --------------------------------------------------
// The Test
// --------------------------------------------------
// --------------------------------------------------
 
pthread_t jposix = -1;
pthread_t j1 = -1;
pthread_t j2 = -1;
pthread_t j3 = -1;
pthread_t j4 = -1;
fsf_server_id_t server1 = -1;
fsf_server_id_t server2 = -1;
fsf_server_id_t server3 = -1;
fsf_server_id_t server4 = -1;
fsf_contract_parameters_t contract;
 
pthread_mutex_t mux;
 
void *posix(void *arg)
{
struct timespec actual,end;
int actpersecond,act;
int cycle;
 
act = 0;
actpersecond = 0;
cycle = 0;
for (;;) {
cycle++;
kern_gettime(&actual);
 
if (act == 0) {
TIMESPEC_ASSIGN(&end,&actual);
end.tv_sec++;
}
 
if (TIMESPEC_A_LT_B(&actual,&end)) {
act++;
} else {
actpersecond = act;
act = 0;
}
 
pthread_mutex_lock(&mux);
printf_xy(0,exec_shadow,GREEN,"Thread %3d Act_per_Second = %8d cycle = %8d",
exec_shadow,actpersecond,cycle);
pthread_mutex_unlock(&mux);
 
}
 
return NULL;
 
}
 
void *star(void *arg)
{
struct timespec actual,end;
int actpersecond,act;
int cycle,rec;
 
act = 0;
actpersecond = 0;
cycle = 0;
rec = 0;
for (;;) {
cycle++;
kern_gettime(&actual);
rec = SERVER_get_last_reclaiming(grubstar_level,exec_shadow);
 
if (act == 0) {
TIMESPEC_ASSIGN(&end,&actual);
end.tv_sec++;
}
 
if (TIMESPEC_A_LT_B(&actual,&end)) {
act++;
} else {
actpersecond = act;
act = 0;
}
 
pthread_mutex_lock(&mux);
printf_xy(0,exec_shadow,WHITE,"Thread %3d Act_per_Second = %8d cycle = %8d rec = %8d",
exec_shadow,actpersecond,cycle,rec);
pthread_mutex_unlock(&mux);
 
}
 
return NULL;
 
}
 
void *periodic_star(void *arg)
{
struct timespec actual,end;
int actpersecond,act;
int cycle,rec;
 
act = 0;
actpersecond = 0;
cycle = 0;
rec = 0;
for (;;) {
cycle++;
kern_gettime(&actual);
rec = SERVER_get_last_reclaiming(grubstar_level,exec_shadow);
 
if (act == 0) {
TIMESPEC_ASSIGN(&end,&actual);
end.tv_sec++;
}
 
if (TIMESPEC_A_LT_B(&actual,&end)) {
act++;
} else {
actpersecond = act;
act = 0;
}
 
pthread_mutex_lock(&mux);
printf_xy(0,exec_shadow,RED,"Thread %3d Act_per_Second = %8d cycle = %8d rec = %8d",
exec_shadow,actpersecond,cycle,rec);
pthread_mutex_unlock(&mux);
 
task_endcycle();
 
}
 
return NULL;
 
}
 
int keyinc = 5;
 
void *edftask(void *arg)
{
long long j;
while(1) {
for (j=0; j<10000*keyinc; j++);
task_endcycle();
}
 
return NULL;
}
 
 
void create()
{
HARD_TASK_MODEL mhard;
int err;
 
struct timespec period1 = {0,90000000}; //30%
struct timespec period2 = {0,300000000}; //20%
struct timespec period3 = {0,300000000}; //10%
struct timespec budget1 = {0,30000000};
struct timespec budget2 = {0,60000000};
struct timespec budget3 = {0,30000000};
PID t1, t2;
 
kern_printf("(Start Create)");
 
hard_task_default_model(mhard);
hard_task_def_ctrl_jet(mhard);
hard_task_def_mit(mhard,30000); //5%
hard_task_def_wcet(mhard,1500);
hard_task_def_arg(mhard,(void *)"X");
hard_task_def_group(mhard,1);
hard_task_def_periodic(mhard);
hard_task_def_level(mhard,0);
t1 = task_create("X", edftask, &mhard, NULL);
if (t1 == NIL) {
perror("Could not create task X ...");
sys_end();
}
 
hard_task_def_mit(mhard,30000); //5%
hard_task_def_wcet(mhard,1500);
hard_task_def_arg(mhard,(void *)"Y");
t2 = task_create("Y", edftask, &mhard, NULL);
if (t2 == NIL) {
perror("Could not create task Y ...");
sys_end();
}
 
group_activate(1);
 
fsf_initialize_contract(&contract);
 
fsf_set_contract_basic_parameters(&contract,&budget1,&period1,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_negotiate_contract(&contract,&server1);
 
fsf_set_contract_basic_parameters(&contract,&budget2,&period2,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_negotiate_contract(&contract,&server2);
 
fsf_set_contract_basic_parameters(&contract,&budget3,&period3,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_negotiate_contract(&contract,&server3);
fsf_set_contract_basic_parameters(&contract,&budget2,&period2,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_set_local_scheduler_parameter(&contract, FSF_SCHEDULER_EDF);
fsf_negotiate_contract(&contract,&server4);
 
err = pthread_create(&jposix, NULL, posix, NULL);
if (err) kern_printf("(Error creating posix task)");
 
kern_printf("(End Create)");
 
}
 
int main(int argc, char **argv)
{
 
int err;
HARD_TASK_MODEL ht;
NRT_TASK_MODEL nrt;
struct timespec endtimer;
 
pthread_mutex_init(&mux,NULL);
 
srand(kern_gettime(NULL));
create();
 
nrt_task_default_model(nrt);
kern_gettime(&endtimer);
endtimer.tv_sec += 20;
kern_event_post(&endtimer, (void (*)(void *))(sys_end), NULL);
 
err = fsf_create_thread(server1,&j1,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
err = fsf_create_thread(server2,&j2,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
err = fsf_create_thread(server3,&j3,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
hard_task_default_model(ht);
hard_task_def_mit(ht,200000);
hard_task_def_wcet(ht,50000);
err = fsf_create_thread(server4,&j4,NULL,periodic_star,NULL,&ht);
kern_printf("(%d)",err);
 
/* hard_task_default_model(ht);
hard_task_def_mit(ht,159000);
hard_task_def_wcet(ht,50000);
err = fsf_create_thread(server4,&j4,NULL,periodic_star,NULL,&ht);
kern_printf("(%d)",err);
*/
err = fsf_create_thread(server1,&j1,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
err = fsf_create_thread(server2,&j2,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
err = fsf_create_thread(server3,&j3,NULL,star,NULL,&nrt);
kern_printf("(%d)",err);
 
return 0;
 
}
 
/advdemos/branches/advdemos/fsf/initfile.c
0,0 → 1,116
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Giacomo Guidi <giacomo@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
/*
* Copyright (C) 2000 Paolo Gai
*
* This program 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.
*
* This program 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
*
*/
 
#include "kernel/kern.h"
#include "modules/edf.h"
#include "modules/cbs.h"
#include "modules/posix.h"
#include "pthread.h"
#include "drivers/keyb.h"
#include "modules/sem.h"
#include "modules/dummy.h"
#include "modules/hartport.h"
 
#include "fsf_contract.h"
#include "fsf_server.h"
 
#include "modules/pi.h"
#include "modules/pc.h"
 
#define TICK 0
 
#define RRTICK 10000
 
void load_file();
 
TIME __kernel_register_levels__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
int grubstar_level;
 
EDF_register_level(EDF_ENABLE_ALL);
POSIX_register_level(RRTICK, 1, mb, 32);
grubstar_level = GRUBSTAR_register_level(FSF_MAX_N_SERVERS, 0);
FSF_register_module(grubstar_level, (int)(MAX_BANDWIDTH * 0.9));
dummy_register_level();
CBS_register_level(CBS_ENABLE_ALL,0);
 
SEM_register_module();
 
PI_register_module();
PC_register_module();
 
PTHREAD_register_module(1, 0, 1);
 
load_file();
 
return TICK;
 
}
 
TASK __init__(void *arg)
{
struct multiboot_info *mb = (struct multiboot_info *)arg;
 
HARTPORT_init();
 
KEYB_init(NULL);
 
__call_main__(mb);
 
return (void *)0;
}
 
int dos_video_preload(void *filename, long max_size, void **start, void **end);
 
void *start_file;
void *end_file;
 
void load_file()
{
start_file = NULL;
end_file = NULL;
dos_video_preload("test.m2v",5000000,&start_file,&end_file);
 
cprintf("Start file ptr = %08lx\n",(long)(start_file));
cprintf("End file ptr = %08lx\n",(long)(end_file));
cprintf("Size = %8ld\n",(long)(end_file - start_file));
 
}
 
/advdemos/branches/advdemos/fsf/demos.txt
0,0 → 1,48
FSF demo for S.Ha.R.K
 
test1.c:
 
This demo shows the main feature of service contract implementation.
 
A set of 4 threads is created using the pthread standard functions.
At the beginning, these threads run without temporal restrictions
and they don't respect any deadline.
 
Two service contracts are initialized and set
 
fsf_initialize_contract(&contract1);
fsf_initialize_contract(&contract2);
fsf_set_contract_basic_parameters(&contract1,&budget1,&period1,NULL,NULL,FSF_DEFAULT_WORKLOAD);
fsf_set_contract_basic_parameters(&contract2,&budget2,&period2,NULL,NULL,FSF_DEFAULT_WORKLOAD);
 
whit the button 'q','w','e' you can respectively
negotiate contract for a server
 
[err = fsf_negotiate_contract(&contractX,&serverY);]
 
'q' -> negotiate contract1 for server1
'w' -> negotiate contract2 for server2
'e' -> negotiate contract1 for server3
 
now with button '1','2','3','4' you can bind the thread to a server
 
[err = fsf_bind_thread_to_server(serverY,jZ);]
 
'1' -> bind thread1 to server1
'2' -> bind thread2 to server2
'3' -> bind thread3 to server3
'4' -> bind thread4 to server2
 
threads will start to respect the assigned budget. It's possible
to bind more threads to one server. The local scheduler specified in the
contract define how the threads will get the server resources.
 
With '5','6','7','8' the thread is unbind from the server
 
[err = fsf_unbind_thread_from_server(jZ);]
 
With 'r','t','y' a server is removed
 
[err = fsf_cancel_contract(&server2);]
 
 
/advdemos/branches/advdemos/fsf/mpeg2/getbits.c
0,0 → 1,217
/* getbits.c, bit level routines */
 
/*
* All modifications (mpeg2decode -> mpeg2play) are
* Copyright (C) 1996, Stefan Eckart. All Rights Reserved.
*/
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdlib.h>
 
#include "drivers/glib.h"
 
#include "config.h"
#include "global.h"
 
/* initialize buffer, call once before first getbits or showbits */
 
void Initialize_Buffer()
{
ld->Incnt = 0;
ld->Rdptr = ld->Rdbfr + 2048;
ld->Rdmax = ld->Rdptr;
 
#ifdef VERIFY
/* only the verifier uses this particular bit counter
* Bitcnt keeps track of the current parser position with respect
* to the video elementary stream being decoded, regardless
* of whether or not it is wrapped within a systems layer stream
*/
ld->Bitcnt = 0;
#endif
 
ld->Bfr = 0;
Flush_Buffer(0); /* fills valid data into bfr */
}
 
int read(int Infile, void *Rdbfr, int rdsize) {
if (ld->actual_file_ptr + 2048 > ld->end_file_ptr)
rdsize = (int)(ld->end_file_ptr - ld->actual_file_ptr);
if (rdsize < 0) return 0;
memcpy(Rdbfr,ld->actual_file_ptr,rdsize);
ld->actual_file_ptr += rdsize;
 
return rdsize;
 
}
void Fill_Buffer()
{
int Buffer_Level;
 
Buffer_Level = read(ld->Infile,ld->Rdbfr,2048);
ld->Rdptr = ld->Rdbfr;
 
if (System_Stream_Flag)
ld->Rdmax -= 2048;
 
/* end of the bitstream file */
if (Buffer_Level < 2048)
{
/* just to be safe */
if (Buffer_Level < 0)
Buffer_Level = 0;
 
/* pad until the next to the next 32-bit word boundary */
while (Buffer_Level & 3)
ld->Rdbfr[Buffer_Level++] = 0;
 
/* pad the buffer with sequence end codes */
while (Buffer_Level < 2048)
{
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>24;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>16;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE>>8;
ld->Rdbfr[Buffer_Level++] = SEQUENCE_END_CODE&0xff;
}
}
}
 
 
/* MPEG-1 system layer demultiplexer */
 
int Get_Byte()
{
while(ld->Rdptr >= ld->Rdbfr+2048)
{
read(ld->Infile,ld->Rdbfr,2048);
ld->Rdptr -= 2048;
ld->Rdmax -= 2048;
}
return *ld->Rdptr++;
}
 
/* extract a 16-bit word from the bitstream buffer */
int Get_Word()
{
int Val;
 
Val = Get_Byte();
return (Val<<8) | Get_Byte();
}
 
 
/* return next n bits (right adjusted) without advancing */
 
unsigned int Show_Bits(N)
int N;
{
return ld->Bfr >> (32-N);
}
 
 
/* return next bit (could be made faster than Get_Bits(1)) */
 
unsigned int Get_Bits1()
{
return Get_Bits(1);
}
 
 
/* advance by n bits */
 
void Flush_Buffer(N)
int N;
{
int Incnt;
 
ld->Bfr <<= N;
 
Incnt = ld->Incnt -= N;
 
if (Incnt <= 24)
{
if (System_Stream_Flag && (ld->Rdptr >= ld->Rdmax-4))
{
do
{
if (ld->Rdptr >= ld->Rdmax)
Next_Packet();
ld->Bfr |= Get_Byte() << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
else if (ld->Rdptr < ld->Rdbfr+2044)
{
do
{
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
else
{
do
{
if (ld->Rdptr >= ld->Rdbfr+2048)
Fill_Buffer();
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
while (Incnt <= 24);
}
ld->Incnt = Incnt;
}
 
#ifdef VERIFY
ld->Bitcnt += N;
#endif /* VERIFY */
 
}
 
 
/* return next n bits (right adjusted) */
 
unsigned int Get_Bits(N)
int N;
{
unsigned int Val;
 
Val = Show_Bits(N);
Flush_Buffer(N);
 
return Val;
}
 
/advdemos/branches/advdemos/fsf/mpeg2/verify.c
0,0 → 1,300
/* verify.c
*
* Bitstream verification routines
*
*
*/
#ifdef VERIFY
 
#include <stdlib.h>
#include <math.h> /* needed for ceil() */
 
#include "config.h"
#include "global.h"
 
/* #define DEBUG */
#ifdef DEBUG
#define PC
#endif
 
#ifdef PC
#include <conio.h> /* needed for getch() */
#endif /* PC */
 
/*
Check picture headers: due to the VBV definition of picture data,
this routine must be called immediately before any picture data
is parsed. (before the first slice start code, including any slice
start code stuffing).
*/
 
 
static void Check_VBV_Delay _ANSI_ARGS_((int Bitstream_Framenum, int Sequence_Framenum));
 
 
void Check_Headers(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum;
int Sequence_Framenum;
{
 
 
if((!low_delay)&&(vbv_delay!=0)&&(vbv_delay!=0xFFFF))
Check_VBV_Delay(Bitstream_Framenum, Sequence_Framenum);
 
/* clear out the header tracking variables so we have an accurate
count next time */
Clear_Verify_Headers();
}
 
 
 
/*
* Verify vbv_delay value in picture header
* (low_delay==1 checks not implemented. this does not exhaustively test all
* possibilities suggested in ISO/IEC 13818-2 Annex C. It only checks
* for constant rate streams)
*
* Q:how do we tell a variable rate stream from a constant rate stream anyway?
* it's not as simple as vbv_delay==0xFFFF, since we need meaningful
* vbv_delay values to calculate the piecewise rate in the first place!
*
* Also: no special provisions at the beginning or end of a sequence
*/
 
static void Check_VBV_Delay(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum;
int Sequence_Framenum;
{
double B; /* buffer size */
double Bn; /* buffer fullness for picture n */
double R; /* bitrate */
double I; /* time interval (t[n+1] - t[n]) */
double T; /* inverse of the frame rate (frame period) */
 
int d;
int internal_vbv_delay;
static int previous_IorP_picture_structure;
static int previous_IorP_repeat_first_field;
static int previous_IorP_top_field_first;
static int previous_vbv_delay;
static int previous_bitstream_position;
 
static double previous_Bn;
static double E; /* maximum quantization error or mismatch */
 
 
if((Sequence_Framenum==0)&&(!Second_Field))
{ /* first coded picture of sequence */
 
R = bit_rate;
 
/* the initial buffer occupancy is taken on faith
that is, we believe what is transmitted in the first coded picture header
to be the true/actual buffer occupancy */
Bn = (R * (double) vbv_delay) / 90000.0;
B = 16 * 1024 * vbv_buffer_size;
 
/* maximum quantization error in bitrate (bit_rate_value is quantized/
rounded-up to units of 400 bits/sec as per ISO/IEC 13818-2
section 6.3.3 */
E = (400.0/frame_rate) + 400;
 
#ifdef DEBUG
cprintf("vbv_buffer_size (B) = %.0f, Bn=%f, E=%f, \nbitrate=%f, vbv_delay=%d frame_rate=%f\n",
B, Bn, E, bit_rate, vbv_delay, frame_rate);
#endif
 
}
else /* not the first coded picture of sequence */
{
 
/* derive the interval (I). The interval tells us how many constant rate bits
* will have been downloaded to the buffer during the current picture period
*
* interval assumes that:
* 1. whilst we are decoding the current I or P picture, we are displaying
* the previous I or P picture which was stored in the reorder
* buffer (pointed to by forward_reference_frame in this implementation)
*
* 2. B pictures are output ("displayed") at the time when they are decoded
*
*/
 
if(progressive_sequence) /* Annex C.9 (progressive_sequence==1, low_delay==0) */
{
 
T = 1/frame_rate; /* inverse of the frame rate (frame period) */
 
if(picture_coding_type==B_TYPE)
{
if(repeat_first_field==1)
{
if(top_field_first==1)
I = T*3; /* three frame periods */
else
I = T*2; /* two frame periods */
}
else
I = T; /* one frame period */
}
else /* P or I frame */
{
if(previous_IorP_repeat_first_field==1)
{
if(previous_IorP_top_field_first==1)
I = 3*T;
else
I = 2*T;
}
else
I = T;
}
}
else /* Annex C.11 (progressive_sequence==0, low_delay==0) */
{
T = 1/(2*frame_rate); /* inverse of two times the frame rate (field period) */
 
if(picture_coding_type==B_TYPE)
{
if(picture_structure==FRAME_PICTURE)
{
if(repeat_first_field==0)
I = 2*T; /* two field periods */
else
I = 3*T; /* three field periods */
}
else /* B field */
{
I = T; /* one field period */
}
}
else /* I or P picture */
{
if(picture_structure==FRAME_PICTURE)
{
if(previous_IorP_repeat_first_field==0)
I = 2*T;
else
I = 3*T;
}
else
{
if(Second_Field==0) /* first field of current frame */
I = T;
else /* second field of current frame */
{
/* formula: previous I or P display period (2*T or 3*T) minus the
very recent decode period (T) of the first field of the current
frame */
 
if(previous_IorP_picture_structure!=FRAME_PICTURE
|| previous_IorP_repeat_first_field==0)
I = 2*T - T; /* a net of one field period */
else if(previous_IorP_picture_structure==FRAME_PICTURE
&& previous_IorP_repeat_first_field==1)
I = 3*T - T; /* a net of two field periods */
}
}
}
}
 
/* derive coded size of previous picture */
d = ld->Bitcnt - previous_bitstream_position;
 
/* Rate = Distance/Time */
 
/* piecewise constant rate (variable rate stream) calculation
* R = ((double) d /((previous_vbv_delay - vbv_delay)/90000 + I));
*/
 
R = bit_rate;
 
/* compute buffer fullness just before removing picture n
*
* Bn = previous_Bn + (I*R) - d; (recursive formula)
*
* where:
*
* n is the current picture
*
* Bn is the buffer fullness for the current picture
*
* previous_Bn is the buffer fullness of the previous picture
*
* (I*R ) is the bits accumulated during the current picture
* period
*
* d is the number of bits removed during the decoding of the
* previous picture
*/
 
Bn = previous_Bn + (I*R) - d;
 
/* compute internally derived vbv_delay (rouding up with ceil()) */
internal_vbv_delay = (int) ceil((90000 * Bn / bit_rate));
 
#ifdef DEBUG
cprintf("\nvbv_delay: internal=%d, bitstream=%d\n", internal_vbv_delay, vbv_delay);
cprintf("Bn=%f, prevBn=%f, I=%f, R=%f, d=%d\n", Bn, previous_Bn, I, R, d);
cprintf("frame(%d), pictstruct(%d), picttype(%d)\n", Sequence_Framenum,
picture_structure, picture_coding_type);
 
/* report error */
if(internal_vbv_delay != vbv_delay)
{
cprintf("WARNING: internal_vbv_delay(%d) != vbv_delay(%d)\n",
internal_vbv_delay, vbv_delay);
}
#endif
 
} /* not the first coded picture of sequence */
 
 
#ifdef PC
getch();
#endif /* PC */
/* update generic tracking variables */
previous_bitstream_position = ld->Bitcnt ;
previous_vbv_delay = vbv_delay;
previous_Bn = Bn;
 
/* reference picture: reordered/delayed output picture */
if(picture_coding_type!=B_TYPE)
{
previous_IorP_repeat_first_field = repeat_first_field;
previous_IorP_top_field_first = top_field_first;
previous_IorP_picture_structure = picture_structure;
}
 
}
 
 
 
/* variables to keep track of the occurance of redundant headers between pictures */
void Clear_Verify_Headers()
{
verify_sequence_header = 0;
verify_group_of_pictures_header = 0;
verify_picture_header = 0;
verify_slice_header = 0;
verify_sequence_extension = 0;
verify_sequence_display_extension = 0;
verify_quant_matrix_extension = 0;
verify_sequence_scalable_extension = 0;
verify_picture_display_extension = 0;
verify_picture_coding_extension = 0;
verify_picture_spatial_scalable_extension = 0;
verify_picture_temporal_scalable_extension = 0;
verify_copyright_extension = 0;
}
 
#endif /* VERIFY */
 
/advdemos/branches/advdemos/fsf/mpeg2/global.h
0,0 → 1,497
/* global.h, global variables */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "ll/sys/types.h"
#include "kernel/kern.h"
#include "mpeg2dec.h"
 
/* choose between declaration (GLOBAL undefined)
* and definition (GLOBAL defined)
* GLOBAL is defined in exactly one file mpeg2dec.c)
*/
 
#ifndef GLOBAL
#define EXTERN extern
#else
#define EXTERN
#endif
 
/* prototypes of global functions */
/* readpic.c */
void Substitute_Frame_Buffer _ANSI_ARGS_ ((int bitstream_framenum,
int sequence_framenum));
 
/* Get_Bits.c */
void Initialize_Buffer _ANSI_ARGS_((void));
void Fill_Buffer _ANSI_ARGS_((void));
unsigned int Show_Bits _ANSI_ARGS_((int n));
unsigned int Get_Bits1 _ANSI_ARGS_((void));
void Flush_Buffer _ANSI_ARGS_((int n));
unsigned int Get_Bits _ANSI_ARGS_((int n));
int Get_Byte _ANSI_ARGS_((void));
int Get_Word _ANSI_ARGS_((void));
 
/* systems.c */
void Next_Packet _ANSI_ARGS_((void));
int Get_Long _ANSI_ARGS_((void));
void Flush_Buffer32 _ANSI_ARGS_((void));
unsigned int Get_Bits32 _ANSI_ARGS_((void));
 
 
/* getblk.c */
void Decode_MPEG1_Intra_Block _ANSI_ARGS_((int comp, int dc_dct_pred[]));
void Decode_MPEG1_Non_Intra_Block _ANSI_ARGS_((int comp));
void Decode_MPEG2_Intra_Block _ANSI_ARGS_((int comp, int dc_dct_pred[]));
void Decode_MPEG2_Non_Intra_Block _ANSI_ARGS_((int comp));
 
/* gethdr.c */
int Get_Hdr _ANSI_ARGS_((void));
void next_start_code _ANSI_ARGS_((void));
int slice_header _ANSI_ARGS_((void));
void marker_bit _ANSI_ARGS_((char *text));
 
/* getpic.c */
void Decode_Picture _ANSI_ARGS_((int bitstream_framenum,
int sequence_framenum));
void Output_Last_Frame_of_Sequence _ANSI_ARGS_((int framenum));
 
/* getvlc.c */
int Get_macroblock_type _ANSI_ARGS_((void));
int Get_motion_code _ANSI_ARGS_((void));
int Get_dmvector _ANSI_ARGS_((void));
int Get_coded_block_pattern _ANSI_ARGS_((void));
int Get_macroblock_address_increment _ANSI_ARGS_((void));
int Get_Luma_DC_dct_diff _ANSI_ARGS_((void));
int Get_Chroma_DC_dct_diff _ANSI_ARGS_((void));
 
/* idct.c */
void Fast_IDCT _ANSI_ARGS_((short *block));
void Initialize_Fast_IDCT _ANSI_ARGS_((void));
 
/* Reference_IDCT.c */
void Initialize_Reference_IDCT _ANSI_ARGS_((void));
void Reference_IDCT _ANSI_ARGS_((short *block));
 
/* motion.c */
void motion_vectors _ANSI_ARGS_((int PMV[2][2][2], int dmvector[2],
int motion_vertical_field_select[2][2], int s, int motion_vector_count,
int mv_format, int h_r_size, int v_r_size, int dmv, int mvscale));
void motion_vector _ANSI_ARGS_((int *PMV, int *dmvector,
int h_r_size, int v_r_size, int dmv, int mvscale, int full_pel_vector));
void Dual_Prime_Arithmetic _ANSI_ARGS_((int DMV[][2], int *dmvector, int mvx, int mvy));
 
/* mpeg2dec.c */
void Error _ANSI_ARGS_((char *text));
void Warning _ANSI_ARGS_((char *text));
void Print_Bits _ANSI_ARGS_((int code, int bits, int len));
 
/* recon.c */
void form_predictions _ANSI_ARGS_((int bx, int by, int macroblock_type,
int motion_type, int PMV[2][2][2], int motion_vertical_field_select[2][2],
int dmvector[2], int stwtype));
 
/* spatscal.c */
void Spatial_Prediction _ANSI_ARGS_((void));
 
/* store.c */
void Write_Frame _ANSI_ARGS_((unsigned char *src[], int frame));
 
#ifdef DISPLAY
/* display.c */
void Initialize_Display_Process _ANSI_ARGS_((char *name));
void Terminate_Display_Process _ANSI_ARGS_((void));
void Display_Second_Field _ANSI_ARGS_((void));
void dither _ANSI_ARGS_((unsigned char *src[]));
void Initialize_Dither_Matrix _ANSI_ARGS_((void));
#endif
 
/* global variables */
 
EXTERN char Version[]
#ifdef GLOBAL
="mpeg2decode V1.2a, 96/07/19"
#endif
;
 
EXTERN char Author[]
#ifdef GLOBAL
="(C) 1996, MPEG Software Simulation Group"
#endif
;
 
 
/* zig-zag and alternate scan patterns */
EXTERN unsigned char scan[2][64]
#ifdef GLOBAL
=
{
{ /* 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
},
{ /* 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
}
}
#endif
;
 
/* default intra quantization matrix */
EXTERN unsigned char default_intra_quantizer_matrix[64]
#ifdef GLOBAL
=
{
8, 16, 19, 22, 26, 27, 29, 34,
16, 16, 22, 24, 27, 29, 34, 37,
19, 22, 26, 27, 29, 34, 34, 38,
22, 22, 26, 27, 29, 34, 37, 40,
22, 26, 27, 29, 32, 35, 40, 48,
26, 27, 29, 32, 35, 40, 48, 58,
26, 27, 29, 34, 38, 46, 56, 69,
27, 29, 35, 38, 46, 56, 69, 83
}
#endif
;
 
/* non-linear quantization coefficient table */
EXTERN unsigned char Non_Linear_quantizer_scale[32]
#ifdef GLOBAL
=
{
0, 1, 2, 3, 4, 5, 6, 7,
8,10,12,14,16,18,20,22,
24,28,32,36,40,44,48,52,
56,64,72,80,88,96,104,112
}
#endif
;
 
/* color space conversion coefficients
* for YCbCr -> RGB mapping
*
* entries are {crv,cbu,cgu,cgv}
*
* crv=(255/224)*65536*(1-cr)/0.5
* cbu=(255/224)*65536*(1-cb)/0.5
* cgu=(255/224)*65536*(cb/cg)*(1-cb)/0.5
* cgv=(255/224)*65536*(cr/cg)*(1-cr)/0.5
*
* where Y=cr*R+cg*G+cb*B (cr+cg+cb=1)
*/
 
/* ISO/IEC 13818-2 section 6.3.6 sequence_display_extension() */
 
EXTERN int Inverse_Table_6_9[8][4]
#ifdef GLOBAL
=
{
{117504, 138453, 13954, 34903}, /* no sequence_display_extension */
{117504, 138453, 13954, 34903}, /* ITU-R Rec. 709 (1990) */
{104597, 132201, 25675, 53279}, /* unspecified */
{104597, 132201, 25675, 53279}, /* reserved */
{104448, 132798, 24759, 53109}, /* FCC */
{104597, 132201, 25675, 53279}, /* ITU-R Rec. 624-4 System B, G */
{104597, 132201, 25675, 53279}, /* SMPTE 170M */
{117579, 136230, 16907, 35559} /* SMPTE 240M (1987) */
}
#endif
;
 
 
 
 
 
/* output types (Output_Type) */
#define T_YUV 0
#define T_SIF 1
#define T_TGA 2
#define T_PPM 3
#define T_X11 4
#define T_X11HIQ 5
 
/* decoder operation control variables */
EXTERN int Output_Type;
EXTERN int hiQdither;
 
/* decoder operation control flags */
EXTERN int Quiet_Flag;
EXTERN int Trace_Flag;
EXTERN int Fault_Flag;
EXTERN int Verbose_Flag;
EXTERN int Two_Streams;
EXTERN int Spatial_Flag;
EXTERN int Reference_IDCT_Flag;
EXTERN int Frame_Store_Flag;
EXTERN int System_Stream_Flag;
EXTERN int Display_Progressive_Flag;
EXTERN int Ersatz_Flag;
EXTERN int Big_Picture_Flag;
EXTERN int Verify_Flag;
EXTERN int Stats_Flag;
EXTERN int User_Data_Flag;
EXTERN int Main_Bitstream_Flag;
 
 
/* filenames */
EXTERN char *Output_Picture_Filename;
EXTERN char *Substitute_Picture_Filename;
EXTERN char *Main_Bitstream_Filename;
EXTERN char *Enhancement_Layer_Bitstream_Filename;
 
 
/* buffers for multiuse purposes */
EXTERN char Error_Text[256];
EXTERN unsigned char *Clip;
 
/* pointers to generic picture buffers */
EXTERN unsigned char *backward_reference_frame[3];
EXTERN unsigned char *forward_reference_frame[3];
 
EXTERN unsigned char *auxframe[3];
EXTERN unsigned char *current_frame[3];
EXTERN unsigned char *substitute_frame[3];
 
 
/* pointers to scalability picture buffers */
EXTERN unsigned char *llframe0[3];
EXTERN unsigned char *llframe1[3];
 
EXTERN short *lltmp;
EXTERN char *Lower_Layer_Picture_Filename;
 
 
 
 
/* non-normative variables derived from normative elements */
EXTERN int Coded_Picture_Width;
EXTERN int Coded_Picture_Height;
EXTERN int Chroma_Width;
EXTERN int Chroma_Height;
EXTERN int block_count;
EXTERN int Second_Field;
EXTERN int profile, level;
 
/* normative derived variables (as per ISO/IEC 13818-2) */
EXTERN int horizontal_size;
EXTERN int vertical_size;
EXTERN int mb_width;
EXTERN int mb_height;
EXTERN double bit_rate;
EXTERN double frame_rate;
 
 
 
/* headers */
 
/* ISO/IEC 13818-2 section 6.2.2.1: sequence_header() */
EXTERN int aspect_ratio_information;
EXTERN int frame_rate_code;
EXTERN int bit_rate_value;
EXTERN int vbv_buffer_size;
EXTERN int constrained_parameters_flag;
 
/* ISO/IEC 13818-2 section 6.2.2.3: sequence_extension() */
EXTERN int profile_and_level_indication;
EXTERN int progressive_sequence;
EXTERN int chroma_format;
EXTERN int low_delay;
EXTERN int frame_rate_extension_n;
EXTERN int frame_rate_extension_d;
 
/* ISO/IEC 13818-2 section 6.2.2.4: sequence_display_extension() */
EXTERN int video_format;
EXTERN int color_description;
EXTERN int color_primaries;
EXTERN int transfer_characteristics;
EXTERN int matrix_coefficients;
EXTERN int display_horizontal_size;
EXTERN int display_vertical_size;
 
/* ISO/IEC 13818-2 section 6.2.3: picture_header() */
EXTERN int temporal_reference;
EXTERN int picture_coding_type;
EXTERN int vbv_delay;
EXTERN int full_pel_forward_vector;
EXTERN int forward_f_code;
EXTERN int full_pel_backward_vector;
EXTERN int backward_f_code;
 
 
/* ISO/IEC 13818-2 section 6.2.3.1: picture_coding_extension() header */
EXTERN int f_code[2][2];
EXTERN int intra_dc_precision;
EXTERN int picture_structure;
EXTERN int top_field_first;
EXTERN int frame_pred_frame_dct;
EXTERN int concealment_motion_vectors;
 
EXTERN int intra_vlc_format;
 
EXTERN int repeat_first_field;
 
EXTERN int chroma_420_type;
EXTERN int progressive_frame;
EXTERN int composite_display_flag;
EXTERN int v_axis;
EXTERN int field_sequence;
EXTERN int sub_carrier;
EXTERN int burst_amplitude;
EXTERN int sub_carrier_phase;
 
 
 
/* ISO/IEC 13818-2 section 6.2.3.3: picture_display_extension() header */
EXTERN int frame_center_horizontal_offset[3];
EXTERN int frame_center_vertical_offset[3];
 
 
 
/* ISO/IEC 13818-2 section 6.2.2.5: sequence_scalable_extension() header */
EXTERN int layer_id;
EXTERN int lower_layer_prediction_horizontal_size;
EXTERN int lower_layer_prediction_vertical_size;
EXTERN int horizontal_subsampling_factor_m;
EXTERN int horizontal_subsampling_factor_n;
EXTERN int vertical_subsampling_factor_m;
EXTERN int vertical_subsampling_factor_n;
 
 
/* ISO/IEC 13818-2 section 6.2.3.5: picture_spatial_scalable_extension() header */
EXTERN int lower_layer_temporal_reference;
EXTERN int lower_layer_horizontal_offset;
EXTERN int lower_layer_vertical_offset;
EXTERN int spatial_temporal_weight_code_table_index;
EXTERN int lower_layer_progressive_frame;
EXTERN int lower_layer_deinterlaced_field_select;
 
 
 
 
 
 
/* ISO/IEC 13818-2 section 6.2.3.6: copyright_extension() header */
EXTERN int copyright_flag;
EXTERN int copyright_identifier;
EXTERN int original_or_copy;
EXTERN int copyright_number_1;
EXTERN int copyright_number_2;
EXTERN int copyright_number_3;
 
/* ISO/IEC 13818-2 section 6.2.2.6: group_of_pictures_header() */
EXTERN int drop_flag;
EXTERN int hour;
EXTERN int minute;
EXTERN int sec;
EXTERN int frame;
EXTERN int closed_gop;
EXTERN int broken_link;
 
 
 
/* layer specific variables (needed for SNR and DP scalability) */
EXTERN struct layer_data {
/* bit input */
int Infile;
 
void *start_file_ptr;
void *actual_file_ptr;
void *end_file_ptr;
int px;
int py;
unsigned char Rdbfr[2048];
unsigned char *Rdptr;
unsigned char Inbfr[16];
/* from mpeg2play */
unsigned int Bfr;
unsigned char *Rdmax;
int Incnt;
int Bitcnt;
/* sequence header and quant_matrix_extension() */
int intra_quantizer_matrix[64];
int non_intra_quantizer_matrix[64];
int chroma_intra_quantizer_matrix[64];
int chroma_non_intra_quantizer_matrix[64];
int load_intra_quantizer_matrix;
int load_non_intra_quantizer_matrix;
int load_chroma_intra_quantizer_matrix;
int load_chroma_non_intra_quantizer_matrix;
 
int MPEG2_Flag;
/* sequence scalable extension */
int scalable_mode;
/* picture coding extension */
int q_scale_type;
int alternate_scan;
/* picture spatial scalable extension */
int pict_scal;
/* slice/macroblock */
int priority_breakpoint;
int quantizer_scale;
int intra_slice;
short block[12][64];
} base, enhan, *ld;
 
#ifdef VERIFY
EXTERN int verify_sequence_header;
EXTERN int verify_group_of_pictures_header;
EXTERN int verify_picture_header;
EXTERN int verify_slice_header;
EXTERN int verify_sequence_extension;
EXTERN int verify_sequence_display_extension;
EXTERN int verify_quant_matrix_extension;
EXTERN int verify_sequence_scalable_extension;
EXTERN int verify_picture_display_extension;
EXTERN int verify_picture_coding_extension;
EXTERN int verify_picture_spatial_scalable_extension;
EXTERN int verify_picture_temporal_scalable_extension;
EXTERN int verify_copyright_extension;
#endif /* VERIFY */
 
 
EXTERN int Decode_Layer;
 
/* verify.c */
#ifdef VERIFY
void Check_Headers _ANSI_ARGS_((int Bitstream_Framenum, int Sequence_Framenum));
void Clear_Verify_Headers _ANSI_ARGS_((void));
#endif /* VERIFY */
 
 
EXTERN int global_MBA;
EXTERN int global_pic;
EXTERN int True_Framenum;
 
/advdemos/branches/advdemos/fsf/mpeg2/motion.c
0,0 → 1,234
/* motion.c, motion vector decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void decode_motion_vector _ANSI_ARGS_((int *pred, int r_size, int motion_code,
int motion_residualesidual, int full_pel_vector));
 
/* ISO/IEC 13818-2 sections 6.2.5.2, 6.3.17.2, and 7.6.3: Motion vectors */
void motion_vectors(PMV,dmvector,
motion_vertical_field_select,s,motion_vector_count,mv_format,h_r_size,v_r_size,dmv,mvscale)
int PMV[2][2][2];
int dmvector[2];
int motion_vertical_field_select[2][2];
int s, motion_vector_count, mv_format, h_r_size, v_r_size, dmv, mvscale;
{
if (motion_vector_count==1)
{
if (mv_format==MV_FIELD && !dmv)
{
motion_vertical_field_select[1][s] = motion_vertical_field_select[0][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
cprintf("motion_vertical_field_select[][%d] (%d): %d\n",s,
motion_vertical_field_select[0][s],motion_vertical_field_select[0][s]);
}
#endif /* TRACE */
}
 
motion_vector(PMV[0][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
 
/* update other motion vector predictors */
PMV[1][s][0] = PMV[0][s][0];
PMV[1][s][1] = PMV[0][s][1];
}
else
{
motion_vertical_field_select[0][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
cprintf("motion_vertical_field_select[0][%d] (%d): %d\n",s,
motion_vertical_field_select[0][s],motion_vertical_field_select[0][s]);
}
#endif /* TRACE */
motion_vector(PMV[0][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
 
motion_vertical_field_select[1][s] = Get_Bits(1);
#ifdef TRACE
if (Trace_Flag)
{
cprintf("motion_vertical_field_select[1][%d] (%d): %d\n",s,
motion_vertical_field_select[1][s],motion_vertical_field_select[1][s]);
}
#endif /* TRACE */
motion_vector(PMV[1][s],dmvector,h_r_size,v_r_size,dmv,mvscale,0);
}
}
 
/* get and decode motion vector and differential motion vector
for one prediction */
void motion_vector(PMV,dmvector,
h_r_size,v_r_size,dmv,mvscale,full_pel_vector)
int *PMV;
int *dmvector;
int h_r_size;
int v_r_size;
int dmv; /* MPEG-2 only: get differential motion vectors */
int mvscale; /* MPEG-2 only: field vector in frame pic */
int full_pel_vector; /* MPEG-1 only */
{
int motion_code, motion_residual;
 
/* horizontal component */
/* ISO/IEC 13818-2 Table B-10 */
motion_code = Get_motion_code();
 
motion_residual = (h_r_size!=0 && motion_code!=0) ? Get_Bits(h_r_size) : 0;
 
#ifdef TRACE
if (Trace_Flag)
{
if (h_r_size!=0 && motion_code!=0)
{
cprintf("motion_residual (");
Print_Bits(motion_residual,h_r_size,h_r_size);
cprintf("): %d\n",motion_residual);
}
}
#endif /* TRACE */
 
 
decode_motion_vector(&PMV[0],h_r_size,motion_code,motion_residual,full_pel_vector);
 
if (dmv)
dmvector[0] = Get_dmvector();
 
 
/* vertical component */
motion_code = Get_motion_code();
motion_residual = (v_r_size!=0 && motion_code!=0) ? Get_Bits(v_r_size) : 0;
 
#ifdef TRACE
if (Trace_Flag)
{
if (v_r_size!=0 && motion_code!=0)
{
cprintf("motion_residual (");
Print_Bits(motion_residual,v_r_size,v_r_size);
cprintf("): %d\n",motion_residual);
}
}
#endif /* TRACE */
 
if (mvscale)
PMV[1] >>= 1; /* DIV 2 */
 
decode_motion_vector(&PMV[1],v_r_size,motion_code,motion_residual,full_pel_vector);
 
if (mvscale)
PMV[1] <<= 1;
 
if (dmv)
dmvector[1] = Get_dmvector();
 
#ifdef TRACE
if (Trace_Flag)
cprintf("PMV = %d,%d\n",PMV[0],PMV[1]);
#endif /* TRACE */
}
 
/* calculate motion vector component */
/* ISO/IEC 13818-2 section 7.6.3.1: Decoding the motion vectors */
/* Note: the arithmetic here is more elegant than that which is shown
in 7.6.3.1. The end results (PMV[][][]) should, however, be the same. */
 
static void decode_motion_vector(pred,r_size,motion_code,motion_residual,full_pel_vector)
int *pred;
int r_size, motion_code, motion_residual;
int full_pel_vector; /* MPEG-1 (ISO/IEC 11172-1) support */
{
int lim, vec;
 
lim = 16<<r_size;
vec = full_pel_vector ? (*pred >> 1) : (*pred);
 
if (motion_code>0)
{
vec+= ((motion_code-1)<<r_size) + motion_residual + 1;
if (vec>=lim)
vec-= lim + lim;
}
else if (motion_code<0)
{
vec-= ((-motion_code-1)<<r_size) + motion_residual + 1;
if (vec<-lim)
vec+= lim + lim;
}
*pred = full_pel_vector ? (vec<<1) : vec;
}
 
 
/* ISO/IEC 13818-2 section 7.6.3.6: Dual prime additional arithmetic */
void Dual_Prime_Arithmetic(DMV,dmvector,mvx,mvy)
int DMV[][2];
int *dmvector; /* differential motion vector */
int mvx, mvy; /* decoded mv components (always in field format) */
{
if (picture_structure==FRAME_PICTURE)
{
if (top_field_first)
{
/* vector for prediction of top field from bottom field */
DMV[0][0] = ((mvx +(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((mvy +(mvy>0))>>1) + dmvector[1] - 1;
 
/* vector for prediction of bottom field from top field */
DMV[1][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
DMV[1][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] + 1;
}
else
{
/* vector for prediction of top field from bottom field */
DMV[0][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] - 1;
 
/* vector for prediction of bottom field from top field */
DMV[1][0] = ((mvx +(mvx>0))>>1) + dmvector[0];
DMV[1][1] = ((mvy +(mvy>0))>>1) + dmvector[1] + 1;
}
}
else
{
/* vector for prediction from field of opposite 'parity' */
DMV[0][0] = ((mvx+(mvx>0))>>1) + dmvector[0];
DMV[0][1] = ((mvy+(mvy>0))>>1) + dmvector[1];
 
/* correct for vertical field shift */
if (picture_structure==TOP_FIELD)
DMV[0][1]--;
else
DMV[0][1]++;
}
}
 
/advdemos/branches/advdemos/fsf/mpeg2/recon.c
0,0 → 1,465
/* Predict.c, motion compensation routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void form_prediction _ANSI_ARGS_((unsigned char *src[], int sfield,
unsigned char *dst[], int dfield,
int lx, int lx2, int w, int h, int x, int y, int dx, int dy,
int average_flag));
 
static void form_component_prediction _ANSI_ARGS_((unsigned char *src, unsigned char *dst,
int lx, int lx2, int w, int h, int x, int y, int dx, int dy, int average_flag));
 
void form_predictions(bx,by,macroblock_type,motion_type,PMV,motion_vertical_field_select,dmvector,stwtype)
int bx, by;
int macroblock_type;
int motion_type;
int PMV[2][2][2], motion_vertical_field_select[2][2], dmvector[2];
int stwtype;
{
int currentfield;
unsigned char **predframe;
int DMV[2][2];
int stwtop, stwbot;
 
stwtop = stwtype%3; /* 0:temporal, 1:(spat+temp)/2, 2:spatial */
stwbot = stwtype/3;
 
if ((macroblock_type & MACROBLOCK_MOTION_FORWARD)
|| (picture_coding_type==P_TYPE))
{
if (picture_structure==FRAME_PICTURE)
{
if ((motion_type==MC_FRAME)
|| !(macroblock_type & MACROBLOCK_MOTION_FORWARD))
{
/* frame-based prediction (broken into top and bottom halves
for spatial scalability prediction purposes) */
if (stwtop<2)
form_prediction(forward_reference_frame,0,current_frame,0,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
 
if (stwbot<2)
form_prediction(forward_reference_frame,1,current_frame,1,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwbot);
}
else if (motion_type==MC_FIELD) /* field-based prediction */
{
/* top field prediction */
if (stwtop<2)
form_prediction(forward_reference_frame,motion_vertical_field_select[0][0],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[0][0][0],PMV[0][0][1]>>1,stwtop);
 
/* bottom field prediction */
if (stwbot<2)
form_prediction(forward_reference_frame,motion_vertical_field_select[1][0],
current_frame,1,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[1][0][0],PMV[1][0][1]>>1,stwbot);
}
else if (motion_type==MC_DMV) /* dual prime prediction */
{
/* calculate derived motion vectors */
Dual_Prime_Arithmetic(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]>>1);
 
if (stwtop<2)
{
/* predict top field from top field */
form_prediction(forward_reference_frame,0,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
PMV[0][0][0],PMV[0][0][1]>>1,0);
 
/* predict and add to top field from bottom field */
form_prediction(forward_reference_frame,1,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
DMV[0][0],DMV[0][1],1);
}
 
if (stwbot<2)
{
/* predict bottom field from bottom field */
form_prediction(forward_reference_frame,1,current_frame,1,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
PMV[0][0][0],PMV[0][0][1]>>1,0);
 
/* predict and add to bottom field from top field */
form_prediction(forward_reference_frame,0,current_frame,1,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by>>1,
DMV[1][0],DMV[1][1],1);
}
}
else
/* invalid motion_type */
cprintf("invalid motion_type\n");
}
else /* TOP_FIELD or BOTTOM_FIELD */
{
/* field picture */
currentfield = (picture_structure==BOTTOM_FIELD);
 
/* determine which frame to use for prediction */
if ((picture_coding_type==P_TYPE) && Second_Field
&& (currentfield!=motion_vertical_field_select[0][0]))
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
if ((motion_type==MC_FIELD)
|| !(macroblock_type & MACROBLOCK_MOTION_FORWARD))
{
/* field-based prediction */
if (stwtop<2)
form_prediction(predframe,motion_vertical_field_select[0][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
}
else if (motion_type==MC_16X8)
{
if (stwtop<2)
{
form_prediction(predframe,motion_vertical_field_select[0][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][0][0],PMV[0][0][1],stwtop);
 
/* determine which frame to use for lower half prediction */
if ((picture_coding_type==P_TYPE) && Second_Field
&& (currentfield!=motion_vertical_field_select[1][0]))
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
form_prediction(predframe,motion_vertical_field_select[1][0],current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,bx,by+8,
PMV[1][0][0],PMV[1][0][1],stwtop);
}
}
else if (motion_type==MC_DMV) /* dual prime prediction */
{
if (Second_Field)
predframe = backward_reference_frame; /* same frame */
else
predframe = forward_reference_frame; /* previous frame */
 
/* calculate derived motion vectors */
Dual_Prime_Arithmetic(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]);
 
/* predict from field of same parity */
form_prediction(forward_reference_frame,currentfield,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
PMV[0][0][0],PMV[0][0][1],0);
 
/* predict from field of opposite parity */
form_prediction(predframe,!currentfield,current_frame,0,
Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,bx,by,
DMV[0][0],DMV[0][1],1);
}
else
/* invalid motion_type */
cprintf("invalid motion_type\n");
}
stwtop = stwbot = 1;
}
 
if (macroblock_type & MACROBLOCK_MOTION_BACKWARD)
{
if (picture_structure==FRAME_PICTURE)
{
if (motion_type==MC_FRAME)
{
/* frame-based prediction */
if (stwtop<2)
form_prediction(backward_reference_frame,0,current_frame,0,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][1][0],PMV[0][1][1],stwtop);
 
if (stwbot<2)
form_prediction(backward_reference_frame,1,current_frame,1,
Coded_Picture_Width,Coded_Picture_Width<<1,16,8,bx,by,
PMV[0][1][0],PMV[0][1][1],stwbot);
}
else /* field-based prediction */
{
/* top field prediction */
if (stwtop<2)
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[0][1][0],PMV[0][1][1]>>1,stwtop);
 
/* bottom field prediction */
if (stwbot<2)
form_prediction(backward_reference_frame,motion_vertical_field_select[1][1],
current_frame,1,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by>>1,PMV[1][1][0],PMV[1][1][1]>>1,stwbot);
}
}
else /* TOP_FIELD or BOTTOM_FIELD */
{
/* field picture */
if (motion_type==MC_FIELD)
{
/* field-based prediction */
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,16,
bx,by,PMV[0][1][0],PMV[0][1][1],stwtop);
}
else if (motion_type==MC_16X8)
{
form_prediction(backward_reference_frame,motion_vertical_field_select[0][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by,PMV[0][1][0],PMV[0][1][1],stwtop);
 
form_prediction(backward_reference_frame,motion_vertical_field_select[1][1],
current_frame,0,Coded_Picture_Width<<1,Coded_Picture_Width<<1,16,8,
bx,by+8,PMV[1][1][0],PMV[1][1][1],stwtop);
}
else
/* invalid motion_type */
cprintf("invalid motion_type\n");
}
}
}
 
static void form_prediction(src,sfield,dst,dfield,lx,lx2,w,h,x,y,dx,dy,average_flag)
unsigned char *src[]; /* prediction source buffer */
int sfield; /* prediction source field number (0 or 1) */
unsigned char *dst[]; /* prediction destination buffer */
int dfield; /* prediction destination field number (0 or 1)*/
int lx,lx2; /* line strides */
int w,h; /* prediction block/sub-block width, height */
int x,y; /* pixel co-ordinates of top-left sample in current MB */
int dx,dy; /* horizontal, vertical prediction address */
int average_flag; /* add prediction error to prediction ? */
{
/* Y */
form_component_prediction(src[0]+(sfield?lx2>>1:0),dst[0]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
 
if (chroma_format!=CHROMA444)
{
lx>>=1; lx2>>=1; w>>=1; x>>=1; dx/=2;
}
 
if (chroma_format==CHROMA420)
{
h>>=1; y>>=1; dy/=2;
}
 
/* Cb */
form_component_prediction(src[1]+(sfield?lx2>>1:0),dst[1]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
 
/* Cr */
form_component_prediction(src[2]+(sfield?lx2>>1:0),dst[2]+(dfield?lx2>>1:0),
lx,lx2,w,h,x,y,dx,dy,average_flag);
}
 
/* ISO/IEC 13818-2 section 7.6.4: Forming predictions */
/* NOTE: the arithmetic below produces numerically equivalent results
* to 7.6.4, yet is more elegant. It differs in the following ways:
*
* 1. the vectors (dx, dy) are based on cartesian frame
* coordiantes along a half-pel grid (always positive numbers)
* In contrast, vector[r][s][t] are differential (with positive and
* negative values). As a result, deriving the integer vectors
* (int_vec[t]) from dx, dy is accomplished by a simple right shift.
*
* 2. Half pel flags (xh, yh) are equivalent to the LSB (Least
* Significant Bit) of the half-pel coordinates (dx,dy).
*
*
* NOTE: the work of combining predictions (ISO/IEC 13818-2 section 7.6.7)
* is distributed among several other stages. This is accomplished by
* folding line offsets into the source and destination (src,dst)
* addresses (note the call arguments to form_prediction() in Predict()),
* line stride variables lx and lx2, the block dimension variables (w,h),
* average_flag, and by the very order in which Predict() is called.
* This implementation design (implicitly different than the spec)
* was chosen for its elegance.
*/
 
static void form_component_prediction(src,dst,lx,lx2,w,h,x,y,dx,dy,average_flag)
unsigned char *src;
unsigned char *dst;
int lx; /* raster line increment */
int lx2;
int w,h;
int x,y;
int dx,dy;
int average_flag; /* flag that signals bi-directional or Dual-Prime
averaging (7.6.7.1 and 7.6.7.4). if average_flag==1,
a previously formed prediction has been stored in
pel_pred[] */
{
int xint; /* horizontal integer sample vector: analogous to int_vec[0] */
int yint; /* vertical integer sample vectors: analogous to int_vec[1] */
int xh; /* horizontal half sample flag: analogous to half_flag[0] */
int yh; /* vertical half sample flag: analogous to half_flag[1] */
int i, j, v;
unsigned char *s; /* source pointer: analogous to pel_ref[][] */
unsigned char *d; /* destination pointer: analogous to pel_pred[][] */
 
/* half pel scaling for integer vectors */
xint = dx>>1;
yint = dy>>1;
 
/* derive half pel flags */
xh = dx & 1;
yh = dy & 1;
 
/* compute the linear address of pel_ref[][] and pel_pred[][]
based on cartesian/raster cordinates provided */
s = src + lx*(y+yint) + x + xint;
d = dst + lx*y + x;
 
if (!xh && !yh) /* no horizontal nor vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i]+s[i];
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = s[i];
}
s+= lx2;
d+= lx2;
}
}
}
else if (!xh && yh) /* no horizontal but vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+lx]+1)>>1);
d[i]=(v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+lx]+1)>>1;
}
 
s+= lx2;
d+= lx2;
}
}
}
else if (xh && !yh) /* horizontal but no vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+1]+1)>>1);
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+1]+1)>>1;
}
 
s+= lx2;
d+= lx2;
}
}
}
else /* if (xh && yh) horizontal and vertical half-pel */
{
if (average_flag)
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v = d[i] + ((unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2);
d[i] = (v+(v>=0?1:0))>>1;
}
s+= lx2;
d+= lx2;
}
}
else
{
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
d[i] = (unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2;
}
 
s+= lx2;
d+= lx2;
}
}
}
}
/advdemos/branches/advdemos/fsf/mpeg2/systems.c
0,0 → 1,195
/* systems.c, systems-specific routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdlib.h>
 
#include "config.h"
#include "global.h"
 
/* initialize buffer, call once before first getbits or showbits */
 
/* parse system layer, ignore everything we don't need */
void Next_Packet()
{
unsigned int code;
int l;
 
for(;;)
{
code = Get_Long();
 
/* remove system layer byte stuffing */
while ((code & 0xffffff00) != 0x100)
code = (code<<8) | Get_Byte();
 
switch(code)
{
case PACK_START_CODE: /* pack header */
/* skip pack header (system_clock_reference and mux_rate) */
ld->Rdptr += 8;
break;
case VIDEO_ELEMENTARY_STREAM:
code = Get_Word(); /* packet_length */
ld->Rdmax = ld->Rdptr + code;
 
code = Get_Byte();
 
if((code>>6)==0x02)
{
ld->Rdptr++;
code=Get_Byte(); /* parse PES_header_data_length */
ld->Rdptr+=code; /* advance pointer by PES_header_data_length */
cprintf("MPEG-2 PES packet\n");
return;
}
else if(code==0xff)
{
/* parse MPEG-1 packet header */
while((code=Get_Byte())== 0xFF);
}
/* stuffing bytes */
if(code>=0x40)
{
if(code>=0x80)
{
cprintf("Error in packet header\n");
}
/* skip STD_buffer_scale */
ld->Rdptr++;
code = Get_Byte();
}
 
if(code>=0x30)
{
if(code>=0x40)
{
cprintf("Error in packet header\n");
}
/* skip presentation and decoding time stamps */
ld->Rdptr += 9;
}
else if(code>=0x20)
{
/* skip presentation time stamps */
ld->Rdptr += 4;
}
else if(code!=0x0f)
{
cprintf("Error in packet header\n");
}
return;
case ISO_END_CODE: /* end */
/* simulate a buffer full of sequence end codes */
l = 0;
while (l<2048)
{
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>24;
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>16;
ld->Rdbfr[l++] = SEQUENCE_END_CODE>>8;
ld->Rdbfr[l++] = SEQUENCE_END_CODE&0xff;
}
ld->Rdptr = ld->Rdbfr;
ld->Rdmax = ld->Rdbfr + 2048;
return;
default:
if(code>=SYSTEM_START_CODE)
{
/* skip system headers and non-video packets*/
code = Get_Word();
ld->Rdptr += code;
}
else
{
cprintf("Unexpected startcode %08x in system layer\n",code);
}
break;
}
}
}
 
 
 
void Flush_Buffer32()
{
int Incnt;
 
ld->Bfr = 0;
 
Incnt = ld->Incnt;
Incnt -= 32;
 
if (System_Stream_Flag && (ld->Rdptr >= ld->Rdmax-4))
{
while (Incnt <= 24)
{
if (ld->Rdptr >= ld->Rdmax)
Next_Packet();
ld->Bfr |= Get_Byte() << (24 - Incnt);
Incnt += 8;
}
}
else
{
while (Incnt <= 24)
{
if (ld->Rdptr >= ld->Rdbfr+2048)
Fill_Buffer();
ld->Bfr |= *ld->Rdptr++ << (24 - Incnt);
Incnt += 8;
}
}
ld->Incnt = Incnt;
 
#ifdef VERIFY
ld->Bitcnt += 32;
#endif /* VERIFY */
}
 
 
unsigned int Get_Bits32()
{
unsigned int l;
 
l = Show_Bits(32);
Flush_Buffer32();
 
return l;
}
 
 
int Get_Long()
{
int i;
 
i = Get_Word();
return (i<<16) | Get_Word();
}
 
 
/advdemos/branches/advdemos/fsf/mpeg2/subspic.c
0,0 → 1,384
/* #define DEBUG */
/* subspic.c, Frame buffer substitution routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdlib.h>
 
#include "config.h"
#include "global.h"
 
/* private prototypes*/
static void Read_Frame _ANSI_ARGS_((char *filename,
unsigned char *frame_buffer[], int framenum));
static void Copy_Frame _ANSI_ARGS_((unsigned char *src, unsigned char *dst,
int width, int height, int parity, int incr));
static int Read_Components _ANSI_ARGS_ ((char *filename,
unsigned char *frame[3], int framenum));
static int Read_Component _ANSI_ARGS_ ((char *fname, unsigned char *frame,
int width, int height));
static int Extract_Components _ANSI_ARGS_ ((char *filename,
unsigned char *frame[3], int framenum));
 
extern int read(int Infile, void *Rdbfr, int rdsize);
 
/* substitute frame buffer routine */
void Substitute_Frame_Buffer (bitstream_framenum, sequence_framenum)
int bitstream_framenum;
int sequence_framenum;
{
/* static tracking variables */
static int previous_temporal_reference;
static int previous_bitstream_framenum;
static int previous_anchor_temporal_reference;
static int previous_anchor_bitstream_framenum;
static int previous_picture_coding_type;
static int bgate;
/* local temporary variables */
int substitute_display_framenum;
 
 
#ifdef DEBUG
cprintf("SUB: seq fn(%d) bitfn(%d) tempref(%d) picstr(%d) type(%d)\n",
sequence_framenum, bitstream_framenum, temporal_reference,
picture_structure, picture_coding_type);
#endif
 
/* we don't substitute at the first picture of a sequence */
if((sequence_framenum!=0)||(Second_Field))
{
/* only at the start of the frame */
if ((picture_structure==FRAME_PICTURE)||(!Second_Field))
{
if(picture_coding_type==P_TYPE)
{
/* the most recently decoded reference frame needs substituting */
substitute_display_framenum = bitstream_framenum - 1;
Read_Frame(Substitute_Picture_Filename, forward_reference_frame,
substitute_display_framenum);
}
/* only the first B frame in a consequitve set of B pictures
loads a substitute backward_reference_frame since all subsequent
B frames predict from the same reference pictures */
else if((picture_coding_type==B_TYPE)&&(bgate!=1))
{
substitute_display_framenum =
(previous_temporal_reference - temporal_reference)
+ bitstream_framenum - 1;
 
Read_Frame(Substitute_Picture_Filename, backward_reference_frame,
substitute_display_framenum);
}
} /* P fields can predict from the two most recently decoded fields, even
from the first field of the same frame being decoded */
else if(Second_Field && (picture_coding_type==P_TYPE))
{
/* our favourite case: the IP field picture pair */
if((previous_picture_coding_type==I_TYPE)&&(picture_coding_type==P_TYPE))
{
substitute_display_framenum = bitstream_framenum;
}
else /* our more generic P field picture pair */
{
substitute_display_framenum =
(temporal_reference - previous_anchor_temporal_reference)
+ bitstream_framenum - 1;
}
 
Read_Frame(Substitute_Picture_Filename, current_frame, substitute_display_framenum);
}
#ifdef DEBUG
else if((picture_coding_type!=B_TYPE)||(picture_coding_type!=D_TYPE))
{
cprintf("NO SUBS FOR THIS PICTURE\n");
}
#endif
}
 
 
/* set b gate so we don't redundantly load next time around */
if(picture_coding_type==B_TYPE)
bgate = 1;
else
bgate = 0;
 
/* update general tracking variables */
if((picture_structure==FRAME_PICTURE)||(!Second_Field))
{
previous_temporal_reference = temporal_reference;
previous_bitstream_framenum = bitstream_framenum;
}
/* update reference frame tracking variables */
if((picture_coding_type!=B_TYPE) &&
((picture_structure==FRAME_PICTURE)||Second_Field))
{
previous_anchor_temporal_reference = temporal_reference;
previous_anchor_bitstream_framenum = bitstream_framenum;
}
 
previous_picture_coding_type = picture_coding_type;
 
}
 
 
/* Note: fields are only read to serve as the same-frame reference for
a second field */
static void Read_Frame(fname,frame,framenum)
char *fname;
unsigned char *frame[];
int framenum;
{
int parity;
int rerr = 0;
int field_mode;
 
if(framenum<0)
cprintf("ERROR: framenum (%d) is less than zero\n", framenum);
 
 
if(Big_Picture_Flag)
rerr = Extract_Components(fname, substitute_frame, framenum);
else
rerr = Read_Components(fname, substitute_frame, framenum);
 
if(rerr!=0)
{
cprintf("was unable to substitute frame\n");
}
 
/* now copy to the appropriate buffer */
/* first field (which we are attempting to substitute) must be
of opposite field parity to the current one */
if((Second_Field)&&(picture_coding_type==P_TYPE))
{
parity = (picture_structure==TOP_FIELD ? 1:0);
field_mode = (picture_structure==FRAME_PICTURE ? 0:1);
}
else
{
/* Like frame structued pictures, B pictures only substitute an entire frame
since both fields always predict from the same frame (with respect
to forward/backwards directions) */
parity = 0;
field_mode = 0;
}
 
 
Copy_Frame(substitute_frame[0], frame[0], Coded_Picture_Width,
Coded_Picture_Height, parity, field_mode);
Copy_Frame(substitute_frame[1], frame[1], Chroma_Width, Chroma_Height,
parity, field_mode);
Copy_Frame(substitute_frame[2], frame[2], Chroma_Width, Chroma_Height,
parity, field_mode);
 
#ifdef VERBOSE
if(Verbose_Flag > NO_LAYER)
cprintf("substituted %s %d\n",
(field_mode ? (parity?"bottom field":"bottom field"):"frame"), framenum);
#endif
}
 
 
 
 
static int Read_Components(filename, frame, framenum)
char *filename;
unsigned char *frame[3];
int framenum;
{
int err = 0;
char outname[FILENAME_LENGTH];
char name[FILENAME_LENGTH];
 
sprintf(outname,filename,framenum);
 
 
sprintf(name,"%s.Y",outname);
err += Read_Component(name, frame[0], Coded_Picture_Width,
Coded_Picture_Height);
 
sprintf(name,"%s.U",outname);
err += Read_Component(name, frame[1], Chroma_Width, Chroma_Height);
 
sprintf(name,"%s.V",outname);
err += Read_Component(name, frame[2], Chroma_Width, Chroma_Height);
 
return(err);
}
 
 
static int Read_Component(Filename, Frame, Width, Height)
char *Filename;
unsigned char *Frame;
int Width;
int Height;
{
int Size;
int Bytes_Read;
int Infile;
 
Size = Width*Height;
 
#ifdef DEBUG
cprintf("SUBS: reading %s\n", filename);
#endif
 
if(!(Infile=1)<0)
{
cprintf("ERROR: unable to open reference filename (%s)\n", Filename);
return(-1);
}
 
Bytes_Read = read(Infile, Frame, Size);
if(Bytes_Read!=Size)
{
cprintf("was able to read only %d bytes of %d of file %s\n",
Bytes_Read, Size, Filename);
}
return(0);
}
 
 
/* optimization: do not open the big file each time. Open once at start
of decoder, and close at the very last frame */
 
/* Note: "big" files were used in E-mail exchanges almost exclusively by the
MPEG Committee's syntax validation and conformance ad-hoc groups from
the year 1993 until 1995 */
static int Extract_Components(filename, frame, framenum)
char *filename;
unsigned char *frame[3];
int framenum;
{
/* int err = 0; */
int line;
int size, offset;
 
cprintf("Extract_Components\n");
/* compute size of each frame (in bytes) */
size = (Coded_Picture_Width*Coded_Picture_Height);
 
if(chroma_format==CHROMA444)
size = (size * 3);
else if(chroma_format==CHROMA422)
size = (size * 2);
else if(chroma_format==CHROMA420)
size = ((size*3)>>1);
else
cprintf("ERROR: chroma_format (%d) not recognized\n", chroma_format);
 
 
/* compute distance into "big" file */
offset = size*framenum;
 
#ifdef DEBUG
printf("EXTRACTING: frame(%d) offset(%d), size (%d) from %s\n",
framenum, offset, size, filename);
#endif
 
/* seek to location in big file where desired frame begins */
/* note: this offset cannot exceed a few billion bytes due to the */
/* obvious limitations of 32-bit integers */
//fseek(fd, offset, 0);
 
/* Y */
for (line=0; line<Coded_Picture_Height; line++)
{
//fread(frame[0]+(line*Coded_Picture_Width),1,Coded_Picture_Width,fd);
}
 
/* Cb */
for (line=0; line<Chroma_Height; line++)
{
//fread(frame[1]+(line*Chroma_Width),1,Chroma_Width,fd);
}
 
/* Cr */
for (line=0; line<Chroma_Height; line++)
{
//fread(frame[2]+(line*Chroma_Width),1,Chroma_Width,fd);
}
 
 
//fclose(fd);
return(0);
}
 
 
static void Copy_Frame(src, dst, width, height, parity, field_mode)
unsigned char *src;
unsigned char *dst;
int width;
int height;
int parity; /* field parity (top or bottom) to overwrite */
int field_mode; /* 0 = frame, 1 = field */
{
int row, col;
int s, d;
int incr;
 
s = d = 0;
 
#ifdef DEBUG
cprintf("COPYING (w=%d, h=%d, parity=%d, field_mode=%d)\n",
width,height,parity,field_mode);
#endif /* DEBUG */
 
if(field_mode)
{
incr = 2;
 
if(parity==0)
s += width;
}
else
{
incr = 1;
}
 
for(row=0; row<height; row+=incr)
{
for(col=0; col<width; col++)
{
dst[d+col] = src[s+col];
}
d += (width*incr);
s += (width*incr);
}
 
}
 
/advdemos/branches/advdemos/fsf/mpeg2/getblk.c
0,0 → 1,571
/* getblk.c, DCT block decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
 
 
/* defined in getvlc.h */
typedef struct {
char run, level, len;
} DCTtab;
 
extern DCTtab DCTtabfirst[],DCTtabnext[],DCTtab0[],DCTtab1[];
extern DCTtab DCTtab2[],DCTtab3[],DCTtab4[],DCTtab5[],DCTtab6[];
extern DCTtab DCTtab0a[],DCTtab1a[];
 
 
/* decode one intra coded MPEG-1 block */
 
void Decode_MPEG1_Intra_Block(comp,dc_dct_pred)
int comp;
int dc_dct_pred[];
{
int val, i, j, sign;
unsigned int code;
DCTtab *tab;
short *bp;
 
bp = ld->block[comp];
 
/* ISO/IEC 11172-2 section 2.4.3.7: Block layer. */
/* decode DC coefficients */
if (comp<4)
bp[0] = (dc_dct_pred[0]+=Get_Luma_DC_dct_diff()) << 3;
else if (comp==4)
bp[0] = (dc_dct_pred[1]+=Get_Chroma_DC_dct_diff()) << 3;
else
bp[0] = (dc_dct_pred[2]+=Get_Chroma_DC_dct_diff()) << 3;
 
if (Fault_Flag) return;
 
/* D-pictures do not contain AC coefficients */
if(picture_coding_type == D_TYPE)
return;
 
/* decode AC coefficients */
for (i=1; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
tab = &DCTtabnext[(code>>12)-4];
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
cprintf("invalid Huffman code in Decode_MPEG1_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
if (tab->run==64) /* end_of_block */
return;
 
if (tab->run==65) /* escape */
{
i+= Get_Bits(6);
 
val = Get_Bits(8);
if (val==0)
val = Get_Bits(8);
else if (val==128)
val = Get_Bits(8) - 256;
else if (val>128)
val -= 256;
 
if((sign = (val<0)))
val = -val;
}
else
{
i+= tab->run;
val = tab->level;
sign = Get_Bits(1);
}
 
if (i>=64)
{
if (!Quiet_Flag)
cprintf("DCT coeff index (i) out of bounds (intra)\n");
Fault_Flag = 1;
return;
}
 
j = scan[ZIG_ZAG][i];
val = (val*ld->quantizer_scale*ld->intra_quantizer_matrix[j]) >> 3;
 
/* mismatch control ('oddification') */
if (val!=0) /* should always be true, but it's not guaranteed */
val = (val-1) | 1; /* equivalent to: if ((val&1)==0) val = val - 1; */
 
/* saturation */
if (!sign)
bp[j] = (val>2047) ? 2047 : val; /* positive */
else
bp[j] = (val>2048) ? -2048 : -val; /* negative */
}
}
 
 
/* decode one non-intra coded MPEG-1 block */
 
void Decode_MPEG1_Non_Intra_Block(comp)
int comp;
{
int val, i, j, sign;
unsigned int code;
DCTtab *tab;
short *bp;
 
bp = ld->block[comp];
 
/* decode AC coefficients */
for (i=0; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
{
if (i==0)
tab = &DCTtabfirst[(code>>12)-4];
else
tab = &DCTtabnext[(code>>12)-4];
}
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
cprintf("invalid Huffman code in Decode_MPEG1_Non_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
if (tab->run==64) /* end_of_block */
return;
 
if (tab->run==65) /* escape */
{
i+= Get_Bits(6);
 
val = Get_Bits(8);
if (val==0)
val = Get_Bits(8);
else if (val==128)
val = Get_Bits(8) - 256;
else if (val>128)
val -= 256;
 
if((sign = (val<0)))
val = -val;
}
else
{
i+= tab->run;
val = tab->level;
sign = Get_Bits(1);
}
 
if (i>=64)
{
if (!Quiet_Flag)
cprintf("DCT coeff index (i) out of bounds (inter)\n");
Fault_Flag = 1;
return;
}
 
j = scan[ZIG_ZAG][i];
val = (((val<<1)+1)*ld->quantizer_scale*ld->non_intra_quantizer_matrix[j]) >> 4;
 
/* mismatch control ('oddification') */
if (val!=0) /* should always be true, but it's not guaranteed */
val = (val-1) | 1; /* equivalent to: if ((val&1)==0) val = val - 1; */
 
/* saturation */
if (!sign)
bp[j] = (val>2047) ? 2047 : val; /* positive */
else
bp[j] = (val>2048) ? -2048 : -val; /* negative */
}
}
 
 
/* decode one intra coded MPEG-2 block */
 
void Decode_MPEG2_Intra_Block(comp,dc_dct_pred)
int comp;
int dc_dct_pred[];
{
int val, i, j, sign, nc, cc, run;
unsigned int code;
DCTtab *tab;
short *bp;
int *qmat;
struct layer_data *ld1;
 
/* with data partitioning, data always goes to base layer */
ld1 = (ld->scalable_mode==SC_DP) ? &base : ld;
bp = ld1->block[comp];
 
if (base.scalable_mode==SC_DP) {
if (base.priority_breakpoint<64)
ld = &enhan;
else
ld = &base;
}
 
cc = (comp<4) ? 0 : (comp&1)+1;
 
qmat = (comp<4 || chroma_format==CHROMA420)
? ld1->intra_quantizer_matrix
: ld1->chroma_intra_quantizer_matrix;
 
/* ISO/IEC 13818-2 section 7.2.1: decode DC coefficients */
if (cc==0)
val = (dc_dct_pred[0]+= Get_Luma_DC_dct_diff());
else if (cc==1)
val = (dc_dct_pred[1]+= Get_Chroma_DC_dct_diff());
else
val = (dc_dct_pred[2]+= Get_Chroma_DC_dct_diff());
 
if (Fault_Flag) return;
 
bp[0] = val << (3-intra_dc_precision);
 
nc=0;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("DCT(%d)i:",comp);
#endif /* TRACE */
 
/* decode AC coefficients */
for (i=1; ; i++)
{
code = Show_Bits(16);
if (code>=16384 && !intra_vlc_format)
tab = &DCTtabnext[(code>>12)-4];
else if (code>=1024)
{
if (intra_vlc_format)
tab = &DCTtab0a[(code>>8)-4];
else
tab = &DCTtab0[(code>>8)-4];
}
else if (code>=512)
{
if (intra_vlc_format)
tab = &DCTtab1a[(code>>6)-8];
else
tab = &DCTtab1[(code>>6)-8];
}
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
cprintf("invalid Huffman code in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
#ifdef TRACE
if (Trace_Flag)
{
printf(" (");
Print_Bits(code,16,tab->len);
}
#endif /* TRACE */
 
if (tab->run==64) /* end_of_block */
{
#ifdef TRACE
if (Trace_Flag)
printf("): EOB\n");
#endif /* TRACE */
return;
}
 
if (tab->run==65) /* escape */
{
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(6),6,6);
}
#endif /* TRACE */
 
i+= run = Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
putchar(' ');
Print_Bits(Show_Bits(12),12,12);
}
#endif /* TRACE */
 
val = Get_Bits(12);
if ((val&2047)==0)
{
if (!Quiet_Flag)
cprintf("invalid escape in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
if((sign = (val>=2048)))
val = 4096 - val;
}
else
{
i+= run = tab->run;
val = tab->level;
sign = Get_Bits(1);
 
#ifdef TRACE
if (Trace_Flag)
cprintf("%d",sign);
#endif /* TRACE */
}
 
if (i>=64)
{
if (!Quiet_Flag)
cprintf("DCT coeff index (i) out of bounds (intra2)\n");
Fault_Flag = 1;
return;
}
 
#ifdef TRACE
if (Trace_Flag)
cprintf("): %d/%d",run,sign ? -val : val);
#endif /* TRACE */
 
j = scan[ld1->alternate_scan][i];
val = (val * ld1->quantizer_scale * qmat[j]) >> 4;
bp[j] = sign ? -val : val;
nc++;
 
if (base.scalable_mode==SC_DP && nc==base.priority_breakpoint-63)
ld = &enhan;
}
}
 
 
/* decode one non-intra coded MPEG-2 block */
 
void Decode_MPEG2_Non_Intra_Block(comp)
int comp;
{
int val, i, j, sign, nc, run;
unsigned int code;
DCTtab *tab;
short *bp;
int *qmat;
struct layer_data *ld1;
 
/* with data partitioning, data always goes to base layer */
ld1 = (ld->scalable_mode==SC_DP) ? &base : ld;
bp = ld1->block[comp];
 
if (base.scalable_mode==SC_DP) {
if (base.priority_breakpoint<64)
ld = &enhan;
else
ld = &base;
}
 
qmat = (comp<4 || chroma_format==CHROMA420)
? ld1->non_intra_quantizer_matrix
: ld1->chroma_non_intra_quantizer_matrix;
 
nc = 0;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("DCT(%d)n:",comp);
#endif /* TRACE */
 
/* decode AC coefficients */
for (i=0; ; i++)
{
code = Show_Bits(16);
if (code>=16384)
{
if (i==0)
tab = &DCTtabfirst[(code>>12)-4];
else
tab = &DCTtabnext[(code>>12)-4];
}
else if (code>=1024)
tab = &DCTtab0[(code>>8)-4];
else if (code>=512)
tab = &DCTtab1[(code>>6)-8];
else if (code>=256)
tab = &DCTtab2[(code>>4)-16];
else if (code>=128)
tab = &DCTtab3[(code>>3)-16];
else if (code>=64)
tab = &DCTtab4[(code>>2)-16];
else if (code>=32)
tab = &DCTtab5[(code>>1)-16];
else if (code>=16)
tab = &DCTtab6[code-16];
else
{
if (!Quiet_Flag)
cprintf("invalid Huffman code in Decode_MPEG2_Non_Intra_Block()\n");
Fault_Flag = 1;
return;
}
 
Flush_Buffer(tab->len);
 
#ifdef TRACE
if (Trace_Flag)
{
cprintf(" (");
Print_Bits(code,16,tab->len);
}
#endif /* TRACE */
 
if (tab->run==64) /* end_of_block */
{
#ifdef TRACE
if (Trace_Flag)
cprintf("): EOB\n");
#endif /* TRACE */
return;
}
 
if (tab->run==65) /* escape */
{
#ifdef TRACE
if (Trace_Flag)
{
cprintf(" ");
Print_Bits(Show_Bits(6),6,6);
}
#endif /* TRACE */
 
i+= run = Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
cprintf(" ");
Print_Bits(Show_Bits(12),12,12);
}
#endif /* TRACE */
 
val = Get_Bits(12);
if ((val&2047)==0)
{
if (!Quiet_Flag)
cprintf("invalid escape in Decode_MPEG2_Intra_Block()\n");
Fault_Flag = 1;
return;
}
if((sign = (val>=2048)))
val = 4096 - val;
}
else
{
i+= run = tab->run;
val = tab->level;
sign = Get_Bits(1);
 
#ifdef TRACE
if (Trace_Flag)
cprintf("%d",sign);
#endif /* TRACE */
}
 
if (i>=64)
{
if (!Quiet_Flag)
cprintf("DCT coeff index (i) out of bounds (inter2)\n");
Fault_Flag = 1;
return;
}
 
#ifdef TRACE
if (Trace_Flag)
cprintf("): %d/%d",run,sign?-val:val);
#endif /* TRACE */
 
j = scan[ld1->alternate_scan][i];
val = (((val<<1)+1) * ld1->quantizer_scale * qmat[j]) >> 5;
bp[j] = sign ? -val : val;
nc++;
 
if (base.scalable_mode==SC_DP && nc==base.priority_breakpoint-63)
ld = &enhan;
}
}
 
/advdemos/branches/advdemos/fsf/mpeg2/spatscal.c
0,0 → 1,275
 
#include "config.h"
#include "global.h"
 
/* private prototypes */
static void Read_Lower_Layer_Component_Framewise _ANSI_ARGS_((int comp, int lw, int lh));
static void Read_Lower_Layer_Component_Fieldwise _ANSI_ARGS_((int comp, int lw, int lh));
static void Make_Spatial_Prediction_Frame _ANSI_ARGS_((int progressive_frame,
int llprogressive_frame, unsigned char *fld0, unsigned char *fld1,
short *tmp, unsigned char *dst, int llx0, int lly0, int llw, int llh,
int horizontal_size, int vertical_size, int vm, int vn, int hm, int hn,
int aperture));
static void Deinterlace _ANSI_ARGS_((unsigned char *fld0, unsigned char *fld1,
int j0, int lx, int ly, int aperture));
static void Subsample_Vertical _ANSI_ARGS_((unsigned char *s, short *d,
int lx, int lys, int lyd, int m, int n, int j0, int dj));
static void Subsample_Horizontal _ANSI_ARGS_((short *s, unsigned char *d,
int x0, int lx, int lxs, int lxd, int ly, int m, int n));
 
 
 
/* get reference frame */
void Spatial_Prediction()
{
if(Frame_Store_Flag)
{
Read_Lower_Layer_Component_Framewise(0,lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size); /* Y */
Read_Lower_Layer_Component_Framewise(1,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cb ("U") */
Read_Lower_Layer_Component_Framewise(2,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cr ("V") */
}
else
{
Read_Lower_Layer_Component_Fieldwise(0,lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size); /* Y */
Read_Lower_Layer_Component_Fieldwise(1,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cb ("U") */
Read_Lower_Layer_Component_Fieldwise(2,lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1); /* Cr ("V") */
}
 
 
Make_Spatial_Prediction_Frame /* Y */
(progressive_frame,lower_layer_progressive_frame,llframe0[0],llframe1[0],
lltmp,current_frame[0],lower_layer_horizontal_offset,
lower_layer_vertical_offset,
lower_layer_prediction_horizontal_size,
lower_layer_prediction_vertical_size,
horizontal_size,vertical_size,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,
picture_structure!=FRAME_PICTURE); /* this changed from CD to DIS */
 
Make_Spatial_Prediction_Frame /* Cb */
(progressive_frame,lower_layer_progressive_frame,llframe0[1],llframe1[1],
lltmp,current_frame[1],lower_layer_horizontal_offset/2,
lower_layer_vertical_offset/2,
lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1,
horizontal_size>>1,vertical_size>>1,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,1);
 
Make_Spatial_Prediction_Frame /* Cr */
(progressive_frame,lower_layer_progressive_frame,llframe0[2],llframe1[2],
lltmp,current_frame[2],lower_layer_horizontal_offset/2,
lower_layer_vertical_offset/2,
lower_layer_prediction_horizontal_size>>1,
lower_layer_prediction_vertical_size>>1,
horizontal_size>>1,vertical_size>>1,vertical_subsampling_factor_m,
vertical_subsampling_factor_n,horizontal_subsampling_factor_m,
horizontal_subsampling_factor_n,1);
 
}
 
static void Read_Lower_Layer_Component_Framewise(comp,lw,lh)
int comp;
int lw, lh;
{
cprintf("Read_Lower_Layer_Component_Framewise\n");
}
 
 
static void Read_Lower_Layer_Component_Fieldwise(comp,lw,lh)
int comp;
int lw, lh;
{
cprintf("Read_Lower_Layer_Component_Fieldwise\n");
}
 
 
/* form spatial prediction */
static void Make_Spatial_Prediction_Frame(progressive_frame,
llprogressive_frame,fld0,fld1,tmp,dst,llx0,lly0,llw,llh,horizontal_size,
vertical_size,vm,vn,hm,hn,aperture)
int progressive_frame,llprogressive_frame;
unsigned char *fld0,*fld1;
short *tmp;
unsigned char *dst;
int llx0,lly0,llw,llh,horizontal_size,vertical_size,vm,vn,hm,hn,aperture;
{
int w, h, x0, llw2, llh2;
 
llw2 = (llw*hn)/hm;
llh2 = (llh*vn)/vm;
 
if (llprogressive_frame)
{
/* progressive -> progressive / interlaced */
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,1);
}
else if (progressive_frame)
{
/* interlaced -> progressive */
if (lower_layer_deinterlaced_field_select)
{
Deinterlace(fld1,fld0,0,llw,llh,aperture);
Subsample_Vertical(fld1,tmp,llw,llh,llh2,vm,vn,0,1);
}
else
{
Deinterlace(fld0,fld1,1,llw,llh,aperture);
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,1);
}
}
else
{
/* interlaced -> interlaced */
Deinterlace(fld0,fld1,1,llw,llh,aperture);
Deinterlace(fld1,fld0,0,llw,llh,aperture);
Subsample_Vertical(fld0,tmp,llw,llh,llh2,vm,vn,0,2);
Subsample_Vertical(fld1,tmp,llw,llh,llh2,vm,vn,1,2);
}
 
/* vertical limits */
if (lly0<0)
{
tmp-= llw*lly0;
llh2+= lly0;
if (llh2<0)
llh2 = 0;
h = (vertical_size<llh2) ? vertical_size : llh2;
}
else
{
dst+= horizontal_size*lly0;
h= vertical_size - lly0;
if (h>llh2)
h = llh2;
}
 
/* horizontal limits */
if (llx0<0)
{
x0 = -llx0;
llw2+= llx0;
if (llw2<0)
llw2 = 0;
w = (horizontal_size<llw2) ? horizontal_size : llw2;
}
else
{
dst+= llx0;
x0 = 0;
w = horizontal_size - llx0;
if (w>llw2)
w = llw2;
}
Subsample_Horizontal(tmp,dst,x0,w,llw,horizontal_size,h,hm,hn);
}
 
/* deinterlace one field (interpolate opposite parity samples)
*
* deinterlacing is done in-place: if j0=1, fld0 contains the input field in
* its even lines and the odd lines are interpolated by this routine
* if j0=0, the input field is in the odd lines and the even lines are
* interpolated
*
* fld0: field to be deinterlaced
* fld1: other field (referenced by the two field aperture filter)
* j0: 0: interpolate even (top) lines, 1: interpolate odd (bottom) lines
* lx: width of fld0 and fld1
* ly: height of the deinterlaced field (has to be even)
* aperture: 1: use one field aperture filter (two field otherwise)
*/
static void Deinterlace(fld0,fld1,j0,lx,ly,aperture)
unsigned char *fld0,*fld1;
int j0,lx,ly; /* ly has to be even */
int aperture;
{
int i,j,v;
unsigned char *p0, *p0m1, *p0p1, *p1, *p1m2, *p1p2;
 
/* deinterlace one field */
for (j=j0; j<ly; j+=2)
{
p0 = fld0+lx*j;
p0m1 = (j==0) ? p0+lx : p0-lx;
p0p1 = (j==ly-1) ? p0-lx : p0+lx;
 
if (aperture)
for (i=0; i<lx; i++)
p0[i] = (unsigned int)(p0m1[i] + p0p1[i] + 1)>>1;
else
{
p1 = fld1 + lx*j;
p1m2 = (j<2) ? p1 : p1-2*lx;
p1p2 = (j>=ly-2) ? p1 : p1+2*lx;
for (i=0; i<lx; i++)
{
v = 8*(p0m1[i]+p0p1[i]) + 2*p1[i] - p1m2[i] - p1p2[i];
p0[i] = Clip[(v + ((v>=0) ? 8 : 7))>>4];
}
}
}
}
 
/* vertical resampling */
static void Subsample_Vertical(s,d,lx,lys,lyd,m,n,j0,dj)
unsigned char *s;
short *d;
int lx, lys, lyd, m, n, j0, dj;
{
int i, j, c1, c2, jd;
unsigned char *s1, *s2;
short *d1;
 
for (j=j0; j<lyd; j+=dj)
{
d1 = d + lx*j;
jd = (j*m)/n;
s1 = s + lx*jd;
s2 = (jd<lys-1)? s1+lx : s1;
c2 = (16*((j*m)%n) + (n>>1))/n;
c1 = 16 - c2;
for (i=0; i<lx; i++)
d1[i] = c1*s1[i] + c2*s2[i];
}
}
 
/* horizontal resampling */
static void Subsample_Horizontal(s,d,x0,lx,lxs,lxd,ly,m,n)
short *s;
unsigned char *d;
int x0, lx, lxs, lxd, ly, m, n;
{
int i, i1, j, id, c1, c2, v;
short *s1, *s2;
unsigned char *d1;
 
for (i1=0; i1<lx; i1++)
{
d1 = d + i1;
i = x0 + i1;
id = (i*m)/n;
s1 = s+id;
s2 = (id<lxs-1) ? s1+1 : s1;
c2 = (16*((i*m)%n) + (n>>1))/n;
c1 = 16 - c2;
for (j=0; j<ly; j++)
{
v = c1*(*s1) + c2*(*s2);
*d1 = (v + ((v>=0) ? 128 : 127))>>8;
d1+= lxd;
s1+= lxs;
s2+= lxs;
}
}
}
 
 
/advdemos/branches/advdemos/fsf/mpeg2/config.h
0,0 → 1,45
/* config.h, configuration defines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* define NON_ANSI_COMPILER for compilers without function prototyping */
/* #define NON_ANSI_COMPILER */
 
#ifdef NON_ANSI_COMPILER
#define _ANSI_ARGS_(x) ()
#else
#define _ANSI_ARGS_(x) x
#endif
 
#define RB "rb"
#define WB "wb"
 
#ifndef O_BINARY
#define O_BINARY 0
 
#endif
/advdemos/branches/advdemos/fsf/mpeg2/getpic.c
0,0 → 1,1223
/* getpic.c, picture decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
 
/* private prototypes*/
static void picture_data _ANSI_ARGS_((int framenum));
static void macroblock_modes _ANSI_ARGS_((int *pmacroblock_type, int *pstwtype,
int *pstwclass, int *pmotion_type, int *pmotion_vector_count, int *pmv_format, int *pdmv,
int *pmvscale, int *pdct_type));
static void Clear_Block _ANSI_ARGS_((int comp));
static void Sum_Block _ANSI_ARGS_((int comp));
static void Saturate _ANSI_ARGS_((short *bp));
static void Add_Block _ANSI_ARGS_((int comp, int bx, int by,
int dct_type, int addflag));
static void Update_Picture_Buffers _ANSI_ARGS_((void));
static void frame_reorder _ANSI_ARGS_((int bitstream_framenum,
int sequence_framenum));
static void Decode_SNR_Macroblock _ANSI_ARGS_((int *SNRMBA, int *SNRMBAinc,
int MBA, int MBAmax, int *dct_type));
 
static void motion_compensation _ANSI_ARGS_((int MBA, int macroblock_type,
int motion_type, int PMV[2][2][2], int motion_vertical_field_select[2][2],
int dmvector[2], int stwtype, int dct_type));
 
static void skipped_macroblock _ANSI_ARGS_((int dc_dct_pred[3],
int PMV[2][2][2], int *motion_type, int motion_vertical_field_select[2][2],
int *stwtype, int *macroblock_type));
 
static int slice _ANSI_ARGS_((int framenum, int MBAmax));
 
static int start_of_slice _ANSI_ARGS_ ((int MBAmax, int *MBA,
int *MBAinc, int dc_dct_pred[3], int PMV[2][2][2]));
 
static int decode_macroblock _ANSI_ARGS_((int *macroblock_type,
int *stwtype, int *stwclass, int *motion_type, int *dct_type,
int PMV[2][2][2], int dc_dct_pred[3],
int motion_vertical_field_select[2][2], int dmvector[2]));
 
 
/* decode one frame or field picture */
void Decode_Picture(bitstream_framenum, sequence_framenum)
int bitstream_framenum, sequence_framenum;
{
 
if (picture_structure==FRAME_PICTURE && Second_Field)
{
/* recover from illegal number of field pictures */
cprintf("odd number of field pictures\n");
Second_Field = 0;
}
 
/* IMPLEMENTATION: update picture buffer pointers */
Update_Picture_Buffers();
 
#ifdef VERIFY
Check_Headers(bitstream_framenum, sequence_framenum);
#endif /* VERIFY */
 
/* ISO/IEC 13818-4 section 2.4.5.4 "frame buffer intercept method" */
/* (section number based on November 1995 (Dallas) draft of the
conformance document) */
if(Ersatz_Flag)
Substitute_Frame_Buffer(bitstream_framenum, sequence_framenum);
 
/* form spatial scalable picture */
/* form spatial scalable picture */
/* ISO/IEC 13818-2 section 7.7: Spatial scalability */
if (base.pict_scal && !Second_Field)
{
Spatial_Prediction();
}
 
/* decode picture data ISO/IEC 13818-2 section 6.2.3.7 */
picture_data(bitstream_framenum);
 
/* write or display current or previously decoded reference frame */
/* ISO/IEC 13818-2 section 6.1.1.11: Frame reordering */
frame_reorder(bitstream_framenum, sequence_framenum);
 
if (picture_structure!=FRAME_PICTURE)
Second_Field = !Second_Field;
}
 
 
/* decode all macroblocks of the current picture */
/* stages described in ISO/IEC 13818-2 section 7 */
static void picture_data(framenum)
int framenum;
{
int MBAmax;
int ret;
 
/* number of macroblocks per picture */
MBAmax = mb_width*mb_height;
 
if (picture_structure!=FRAME_PICTURE)
MBAmax>>=1; /* field picture has half as mnay macroblocks as frame */
 
for(;;)
{
if((ret=slice(framenum, MBAmax))<0)
return;
}
 
}
 
 
 
/* decode all macroblocks of the current picture */
/* ISO/IEC 13818-2 section 6.3.16 */
static int slice(framenum, MBAmax)
int framenum, MBAmax;
{
int MBA;
int MBAinc, macroblock_type, motion_type, dct_type;
int dc_dct_pred[3];
int PMV[2][2][2], motion_vertical_field_select[2][2];
int dmvector[2];
int stwtype, stwclass;
int SNRMBA, SNRMBAinc;
int ret;
 
MBA = 0; /* macroblock address */
MBAinc = 0;
 
if((ret=start_of_slice(MBAmax, &MBA, &MBAinc, dc_dct_pred, PMV))!=1)
return(ret);
 
if (Two_Streams && enhan.scalable_mode==SC_SNR)
{
SNRMBA=0;
SNRMBAinc=0;
}
 
Fault_Flag=0;
 
for (;;)
{
 
/* this is how we properly exit out of picture */
if (MBA>=MBAmax)
return(-1); /* all macroblocks decoded */
 
#ifdef TRACE
if (Trace_Flag)
cprintf("frame %d, MB %d\n",framenum,MBA);
#endif /* TRACE */
 
#ifdef DISPLAY
if (!progressive_frame && picture_structure==FRAME_PICTURE
&& MBA==(MBAmax>>1) && framenum!=0 && Output_Type==T_X11
&& !Display_Progressive_Flag)
{
Display_Second_Field();
}
#endif
 
ld = &base;
 
if (MBAinc==0)
{
if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
ld = &enhan;
 
if (!Show_Bits(23) || Fault_Flag) /* next_start_code or fault */
{
resync: /* if Fault_Flag: resynchronize to next next_start_code */
Fault_Flag = 0;
return(0); /* trigger: go to next slice */
}
else /* neither next_start_code nor Fault_Flag */
{
if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
ld = &enhan;
 
/* decode macroblock address increment */
MBAinc = Get_macroblock_address_increment();
 
if (Fault_Flag) goto resync;
}
}
 
if (MBA>=MBAmax)
{
/* MBAinc points beyond picture dimensions */
if (!Quiet_Flag)
cprintf("Too many macroblocks in picture\n");
return(-1);
}
 
if (MBAinc==1) /* not skipped */
{
ret = decode_macroblock(&macroblock_type, &stwtype, &stwclass,
&motion_type, &dct_type, PMV, dc_dct_pred,
motion_vertical_field_select, dmvector);
 
if(ret==-1)
return(-1);
if(ret==0)
goto resync;
 
}
else /* MBAinc!=1: skipped macroblock */
{
/* ISO/IEC 13818-2 section 7.6.6 */
skipped_macroblock(dc_dct_pred, PMV, &motion_type,
motion_vertical_field_select, &stwtype, &macroblock_type);
}
 
/* SCALABILITY: SNR */
/* ISO/IEC 13818-2 section 7.8 */
/* NOTE: we currently ignore faults encountered in this routine */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
Decode_SNR_Macroblock(&SNRMBA, &SNRMBAinc, MBA, MBAmax, &dct_type);
 
/* ISO/IEC 13818-2 section 7.6 */
motion_compensation(MBA, macroblock_type, motion_type, PMV,
motion_vertical_field_select, dmvector, stwtype, dct_type);
 
 
/* advance to next macroblock */
MBA++;
MBAinc--;
/* SCALABILITY: SNR */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
{
SNRMBA++;
SNRMBAinc--;
}
 
if (MBA>=MBAmax)
return(-1); /* all macroblocks decoded */
}
}
 
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
static void macroblock_modes(pmacroblock_type,pstwtype,pstwclass,
pmotion_type,pmotion_vector_count,pmv_format,pdmv,pmvscale,pdct_type)
int *pmacroblock_type, *pstwtype, *pstwclass;
int *pmotion_type, *pmotion_vector_count, *pmv_format, *pdmv, *pmvscale;
int *pdct_type;
{
int macroblock_type;
int stwtype, stwcode, stwclass;
int motion_type = 0;
int motion_vector_count, mv_format, dmv, mvscale;
int dct_type;
static unsigned char stwc_table[3][4]
= { {6,3,7,4}, {2,1,5,4}, {2,5,7,4} };
static unsigned char stwclass_table[9]
= {0, 1, 2, 1, 1, 2, 3, 3, 4};
 
/* get macroblock_type */
macroblock_type = Get_macroblock_type();
 
if (Fault_Flag) return;
 
/* get spatial_temporal_weight_code */
if (macroblock_type & MB_WEIGHT)
{
if (spatial_temporal_weight_code_table_index==0)
stwtype = 4;
else
{
stwcode = Get_Bits(2);
#ifdef TRACE
if (Trace_Flag)
{
cprintf("spatial_temporal_weight_code (");
Print_Bits(stwcode,2,2);
cprintf("): %d\n",stwcode);
}
#endif /* TRACE */
stwtype = stwc_table[spatial_temporal_weight_code_table_index-1][stwcode];
}
}
else
stwtype = (macroblock_type & MB_CLASS4) ? 8 : 0;
 
/* SCALABILITY: derive spatial_temporal_weight_class (Table 7-18) */
stwclass = stwclass_table[stwtype];
 
/* get frame/field motion type */
if (macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD))
{
if (picture_structure==FRAME_PICTURE) /* frame_motion_type */
{
motion_type = frame_pred_frame_dct ? MC_FRAME : Get_Bits(2);
#ifdef TRACE
if (!frame_pred_frame_dct && Trace_Flag)
{
cprintf("frame_motion_type (");
Print_Bits(motion_type,2,2);
cprintf("): %s\n",motion_type==MC_FIELD?"Field":
motion_type==MC_FRAME?"Frame":
motion_type==MC_DMV?"Dual_Prime":"Invalid");
}
#endif /* TRACE */
}
else /* field_motion_type */
{
motion_type = Get_Bits(2);
#ifdef TRACE
if (Trace_Flag)
{
cprintf("field_motion_type (");
Print_Bits(motion_type,2,2);
cprintf("): %s\n",motion_type==MC_FIELD?"Field":
motion_type==MC_16X8?"16x8 MC":
motion_type==MC_DMV?"Dual_Prime":"Invalid");
}
#endif /* TRACE */
}
}
else if ((macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
{
/* concealment motion vectors */
motion_type = (picture_structure==FRAME_PICTURE) ? MC_FRAME : MC_FIELD;
}
#if 0
else
{
printf("maroblock_modes(): unknown macroblock type\n");
motion_type = -1;
}
#endif
 
/* derive motion_vector_count, mv_format and dmv, (table 6-17, 6-18) */
if (picture_structure==FRAME_PICTURE)
{
motion_vector_count = (motion_type==MC_FIELD && stwclass<2) ? 2 : 1;
mv_format = (motion_type==MC_FRAME) ? MV_FRAME : MV_FIELD;
}
else
{
motion_vector_count = (motion_type==MC_16X8) ? 2 : 1;
mv_format = MV_FIELD;
}
 
dmv = (motion_type==MC_DMV); /* dual prime */
 
/* field mv predictions in frame pictures have to be scaled
* ISO/IEC 13818-2 section 7.6.3.1 Decoding the motion vectors
* IMPLEMENTATION: mvscale is derived for later use in motion_vectors()
* it displaces the stage:
*
* if((mv_format=="field")&&(t==1)&&(picture_structure=="Frame picture"))
* prediction = PMV[r][s][t] DIV 2;
*/
 
mvscale = ((mv_format==MV_FIELD) && (picture_structure==FRAME_PICTURE));
 
/* get dct_type (frame DCT / field DCT) */
dct_type = (picture_structure==FRAME_PICTURE)
&& (!frame_pred_frame_dct)
&& (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA))
? Get_Bits(1)
: 0;
 
#ifdef TRACE
if (Trace_Flag && (picture_structure==FRAME_PICTURE)
&& (!frame_pred_frame_dct)
&& (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA)))
cprintf("dct_type (%d): %s\n",dct_type,dct_type?"Field":"Frame");
#endif /* TRACE */
 
/* return values */
*pmacroblock_type = macroblock_type;
*pstwtype = stwtype;
*pstwclass = stwclass;
*pmotion_type = motion_type;
*pmotion_vector_count = motion_vector_count;
*pmv_format = mv_format;
*pdmv = dmv;
*pmvscale = mvscale;
*pdct_type = dct_type;
}
 
 
/* move/add 8x8-Block from block[comp] to backward_reference_frame */
/* copy reconstructed 8x8 block from block[comp] to current_frame[]
* ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data
* This stage also embodies some of the operations implied by:
* - ISO/IEC 13818-2 section 7.6.7: Combining predictions
* - ISO/IEC 13818-2 section 6.1.3: Macroblock
*/
static void Add_Block(comp,bx,by,dct_type,addflag)
int comp,bx,by,dct_type,addflag;
{
int cc,i, j, iincr;
unsigned char *rfp;
short *bp;
 
/* derive color component index */
/* equivalent to ISO/IEC 13818-2 Table 7-1 */
cc = (comp<4) ? 0 : (comp&1)+1; /* color component index */
 
if (cc==0)
{
/* luminance */
 
if (picture_structure==FRAME_PICTURE)
if (dct_type)
{
/* field DCT coding */
rfp = current_frame[0]
+ Coded_Picture_Width*(by+((comp&2)>>1)) + bx + ((comp&1)<<3);
iincr = (Coded_Picture_Width<<1) - 8;
}
else
{
/* frame DCT coding */
rfp = current_frame[0]
+ Coded_Picture_Width*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
iincr = Coded_Picture_Width - 8;
}
else
{
/* field picture */
rfp = current_frame[0]
+ (Coded_Picture_Width<<1)*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
iincr = (Coded_Picture_Width<<1) - 8;
}
}
else
{
/* chrominance */
 
/* scale coordinates */
if (chroma_format!=CHROMA444)
bx >>= 1;
if (chroma_format==CHROMA420)
by >>= 1;
if (picture_structure==FRAME_PICTURE)
{
if (dct_type && (chroma_format!=CHROMA420))
{
/* field DCT coding */
rfp = current_frame[cc]
+ Chroma_Width*(by+((comp&2)>>1)) + bx + (comp&8);
iincr = (Chroma_Width<<1) - 8;
}
else
{
/* frame DCT coding */
rfp = current_frame[cc]
+ Chroma_Width*(by+((comp&2)<<2)) + bx + (comp&8);
iincr = Chroma_Width - 8;
}
}
else
{
/* field picture */
rfp = current_frame[cc]
+ (Chroma_Width<<1)*(by+((comp&2)<<2)) + bx + (comp&8);
iincr = (Chroma_Width<<1) - 8;
}
}
 
bp = ld->block[comp];
 
if (addflag)
{
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
{
*rfp = Clip[*bp++ + *rfp];
rfp++;
}
 
rfp+= iincr;
}
}
else
{
for (i=0; i<8; i++)
{
for (j=0; j<8; j++)
*rfp++ = Clip[*bp++ + 128];
 
rfp+= iincr;
}
}
}
 
 
/* ISO/IEC 13818-2 section 7.8 */
static void Decode_SNR_Macroblock(SNRMBA, SNRMBAinc, MBA, MBAmax, dct_type)
int *SNRMBA, *SNRMBAinc;
int MBA, MBAmax;
int *dct_type;
{
int SNRmacroblock_type, SNRcoded_block_pattern, SNRdct_type, dummy;
int slice_vert_pos_ext, quantizer_scale_code, comp, code;
 
ld = &enhan;
 
if (*SNRMBAinc==0)
{
if (!Show_Bits(23)) /* next_start_code */
{
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
cprintf("SNR: Premature end of picture\n");
return;
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
/* decode macroblock address increment */
*SNRMBAinc = Get_macroblock_address_increment();
 
/* set current location */
*SNRMBA =
((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *SNRMBAinc - 1;
 
*SNRMBAinc = 1; /* first macroblock in slice: not skipped */
}
else /* not next_start_code */
{
if (*SNRMBA>=MBAmax)
{
if (!Quiet_Flag)
cprintf("Too many macroblocks in picture\n");
return;
}
 
/* decode macroblock address increment */
*SNRMBAinc = Get_macroblock_address_increment();
}
}
 
if (*SNRMBA!=MBA)
{
/* streams out of sync */
if (!Quiet_Flag)
cprintf("Cant't synchronize streams\n");
return;
}
 
if (*SNRMBAinc==1) /* not skipped */
{
macroblock_modes(&SNRmacroblock_type, &dummy, &dummy,
&dummy, &dummy, &dummy, &dummy, &dummy,
&SNRdct_type);
 
if (SNRmacroblock_type & MACROBLOCK_PATTERN)
*dct_type = SNRdct_type;
 
if (SNRmacroblock_type & MACROBLOCK_QUANT)
{
quantizer_scale_code = Get_Bits(5);
ld->quantizer_scale =
ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] : quantizer_scale_code<<1;
}
 
/* macroblock_pattern */
if (SNRmacroblock_type & MACROBLOCK_PATTERN)
{
SNRcoded_block_pattern = Get_coded_block_pattern();
 
if (chroma_format==CHROMA422)
SNRcoded_block_pattern = (SNRcoded_block_pattern<<2) | Get_Bits(2); /* coded_block_pattern_1 */
else if (chroma_format==CHROMA444)
SNRcoded_block_pattern = (SNRcoded_block_pattern<<6) | Get_Bits(6); /* coded_block_pattern_2 */
}
else
SNRcoded_block_pattern = 0;
 
/* decode blocks */
for (comp=0; comp<block_count; comp++)
{
Clear_Block(comp);
 
if (SNRcoded_block_pattern & (1<<(block_count-1-comp)))
Decode_MPEG2_Non_Intra_Block(comp);
}
}
else /* SNRMBAinc!=1: skipped macroblock */
{
for (comp=0; comp<block_count; comp++)
Clear_Block(comp);
}
 
ld = &base;
}
 
 
 
/* IMPLEMENTATION: set scratch pad macroblock to zero */
static void Clear_Block(comp)
int comp;
{
short *Block_Ptr;
int i;
 
Block_Ptr = ld->block[comp];
 
for (i=0; i<64; i++)
*Block_Ptr++ = 0;
}
 
 
/* SCALABILITY: add SNR enhancement layer block data to base layer */
/* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from the two layes */
static void Sum_Block(comp)
int comp;
{
short *Block_Ptr1, *Block_Ptr2;
int i;
 
Block_Ptr1 = base.block[comp];
Block_Ptr2 = enhan.block[comp];
 
for (i=0; i<64; i++)
*Block_Ptr1++ += *Block_Ptr2++;
}
 
 
/* limit coefficients to -2048..2047 */
/* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
static void Saturate(Block_Ptr)
short *Block_Ptr;
{
int i, sum, val;
 
sum = 0;
 
/* ISO/IEC 13818-2 section 7.4.3: Saturation */
for (i=0; i<64; i++)
{
val = Block_Ptr[i];
 
if (val>2047)
val = 2047;
else if (val<-2048)
val = -2048;
 
Block_Ptr[i] = val;
sum+= val;
}
 
/* ISO/IEC 13818-2 section 7.4.4: Mismatch control */
if ((sum&1)==0)
Block_Ptr[63]^= 1;
 
}
 
 
/* reuse old picture buffers as soon as they are no longer needed
based on life-time axioms of MPEG */
static void Update_Picture_Buffers()
{
int cc; /* color component index */
unsigned char *tmp; /* temporary swap pointer */
 
for (cc=0; cc<3; cc++)
{
/* B pictures do not need to be save for future reference */
if (picture_coding_type==B_TYPE)
{
current_frame[cc] = auxframe[cc];
}
else
{
/* only update at the beginning of the coded frame */
if (!Second_Field)
{
tmp = forward_reference_frame[cc];
 
/* the previously decoded reference frame is stored
coincident with the location where the backward
reference frame is stored (backwards prediction is not
needed in P pictures) */
forward_reference_frame[cc] = backward_reference_frame[cc];
/* update pointer for potential future B pictures */
backward_reference_frame[cc] = tmp;
}
 
/* can erase over old backward reference frame since it is not used
in a P picture, and since any subsequent B pictures will use the
previously decoded I or P frame as the backward_reference_frame */
current_frame[cc] = backward_reference_frame[cc];
}
 
/* IMPLEMENTATION:
one-time folding of a line offset into the pointer which stores the
memory address of the current frame saves offsets and conditional
branches throughout the remainder of the picture processing loop */
if (picture_structure==BOTTOM_FIELD)
current_frame[cc]+= (cc==0) ? Coded_Picture_Width : Chroma_Width;
}
}
 
 
/* store last frame */
 
void Output_Last_Frame_of_Sequence(Framenum)
int Framenum;
{
if (Second_Field)
cprintf("last frame incomplete, not stored\n");
else
Write_Frame(backward_reference_frame,Framenum-1);
}
 
 
 
static void frame_reorder(Bitstream_Framenum, Sequence_Framenum)
int Bitstream_Framenum, Sequence_Framenum;
{
/* tracking variables to insure proper output in spatial scalability */
static int Oldref_progressive_frame, Newref_progressive_frame;
 
if (Sequence_Framenum!=0)
{
if (picture_structure==FRAME_PICTURE || Second_Field)
{
if (picture_coding_type==B_TYPE)
Write_Frame(auxframe,Bitstream_Framenum-1);
else
{
Newref_progressive_frame = progressive_frame;
progressive_frame = Oldref_progressive_frame;
 
Write_Frame(forward_reference_frame,Bitstream_Framenum-1);
 
Oldref_progressive_frame = progressive_frame = Newref_progressive_frame;
}
}
#ifdef DISPLAY
else if (Output_Type==T_X11)
{
if(!Display_Progressive_Flag)
Display_Second_Field();
}
#endif
}
else
Oldref_progressive_frame = progressive_frame;
 
}
 
 
/* ISO/IEC 13818-2 section 7.6 */
static void motion_compensation(MBA, macroblock_type, motion_type, PMV,
motion_vertical_field_select, dmvector, stwtype, dct_type)
int MBA;
int macroblock_type;
int motion_type;
int PMV[2][2][2];
int motion_vertical_field_select[2][2];
int dmvector[2];
int stwtype;
int dct_type;
{
int bx, by;
int comp;
 
/* derive current macroblock position within picture */
/* ISO/IEC 13818-2 section 6.3.1.6 and 6.3.1.7 */
bx = 16*(MBA%mb_width);
by = 16*(MBA/mb_width);
 
/* motion compensation */
if (!(macroblock_type & MACROBLOCK_INTRA))
form_predictions(bx,by,macroblock_type,motion_type,PMV,
motion_vertical_field_select,dmvector,stwtype);
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
/* copy or add block data into picture */
for (comp=0; comp<block_count; comp++)
{
/* SCALABILITY: SNR */
/* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from
the two a layers */
if (Two_Streams && enhan.scalable_mode==SC_SNR)
Sum_Block(comp); /* add SNR enhancement layer data to base layer */
 
/* MPEG-2 saturation and mismatch control */
/* base layer could be MPEG-1 stream, enhancement MPEG-2 SNR */
/* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
if ((Two_Streams && enhan.scalable_mode==SC_SNR) || ld->MPEG2_Flag)
Saturate(ld->block[comp]);
 
/* ISO/IEC 13818-2 section Annex A: inverse DCT */
if (Reference_IDCT_Flag)
Reference_IDCT(ld->block[comp]);
else
Fast_IDCT(ld->block[comp]);
/* ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data */
Add_Block(comp,bx,by,dct_type,(macroblock_type & MACROBLOCK_INTRA)==0);
}
 
}
 
 
 
/* ISO/IEC 13818-2 section 7.6.6 */
static void skipped_macroblock(dc_dct_pred, PMV, motion_type,
motion_vertical_field_select, stwtype, macroblock_type)
int dc_dct_pred[3];
int PMV[2][2][2];
int *motion_type;
int motion_vertical_field_select[2][2];
int *stwtype;
int *macroblock_type;
{
int comp;
/* SCALABILITY: Data Paritioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
for (comp=0; comp<block_count; comp++)
Clear_Block(comp);
 
/* reset intra_dc predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
 
/* reset motion vector predictors */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
if (picture_coding_type==P_TYPE)
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
 
/* derive motion_type */
if (picture_structure==FRAME_PICTURE)
*motion_type = MC_FRAME;
else
{
*motion_type = MC_FIELD;
 
/* predict from field of same parity */
/* ISO/IEC 13818-2 section 7.6.6.1 and 7.6.6.3: P field picture and B field
picture */
motion_vertical_field_select[0][0]=motion_vertical_field_select[0][1] =
(picture_structure==BOTTOM_FIELD);
}
 
/* skipped I are spatial-only predicted, */
/* skipped P and B are temporal-only predicted */
/* ISO/IEC 13818-2 section 7.7.6: Skipped macroblocks */
*stwtype = (picture_coding_type==I_TYPE) ? 8 : 0;
 
/* IMPLEMENTATION: clear MACROBLOCK_INTRA */
*macroblock_type&= ~MACROBLOCK_INTRA;
 
}
 
 
/* return==-1 means go to next picture */
/* the expression "start of slice" is used throughout the normative
body of the MPEG specification */
static int start_of_slice(MBAmax, MBA, MBAinc,
dc_dct_pred, PMV)
int MBAmax;
int *MBA;
int *MBAinc;
int dc_dct_pred[3];
int PMV[2][2][2];
{
unsigned int code;
int slice_vert_pos_ext;
 
ld = &base;
 
Fault_Flag = 0;
 
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
cprintf("start_of_slice(): Premature end of picture\n");
 
return(-1); /* trigger: go to next picture */
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
{
ld = &enhan;
next_start_code();
code = Show_Bits(32);
 
if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
{
/* only slice headers are allowed in picture_data */
if (!Quiet_Flag)
cprintf("DP: Premature end of picture\n");
return(-1); /* trigger: go to next picture */
}
 
Flush_Buffer32();
 
/* decode slice header (may change quantizer_scale) */
slice_vert_pos_ext = slice_header();
 
if (base.priority_breakpoint!=1)
ld = &base;
}
 
/* decode macroblock address increment */
*MBAinc = Get_macroblock_address_increment();
 
if (Fault_Flag)
{
cprintf("start_of_slice(): MBAinc unsuccessful\n");
return(0); /* trigger: go to next slice */
}
 
/* set current location */
/* NOTE: the arithmetic used to derive macroblock_address below is
* equivalent to ISO/IEC 13818-2 section 6.3.17: Macroblock
*/
*MBA = ((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *MBAinc - 1;
*MBAinc = 1; /* first macroblock in slice: not skipped */
 
/* reset all DC coefficient and motion vector predictors */
/* reset all DC coefficient and motion vector predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
 
/* successfull: trigger decode macroblocks in slice */
return(1);
}
 
 
/* ISO/IEC 13818-2 sections 7.2 through 7.5 */
static int decode_macroblock(macroblock_type, stwtype, stwclass,
motion_type, dct_type, PMV, dc_dct_pred,
motion_vertical_field_select, dmvector)
int *macroblock_type;
int *stwtype;
int *stwclass;
int *motion_type;
int *dct_type;
int PMV[2][2][2];
int dc_dct_pred[3];
int motion_vertical_field_select[2][2];
int dmvector[2];
{
/* locals */
int quantizer_scale_code;
int comp;
 
int motion_vector_count;
int mv_format;
int dmv;
int mvscale;
int coded_block_pattern;
 
/* SCALABILITY: Data Patitioning */
if (base.scalable_mode==SC_DP)
{
if (base.priority_breakpoint<=2)
ld = &enhan;
else
ld = &base;
}
 
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
macroblock_modes(macroblock_type, stwtype, stwclass,
motion_type, &motion_vector_count, &mv_format, &dmv, &mvscale,
dct_type);
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
if (*macroblock_type & MACROBLOCK_QUANT)
{
quantizer_scale_code = Get_Bits(5);
 
#ifdef TRACE
if (Trace_Flag)
{
cprintf("quantiser_scale_code (");
Print_Bits(quantizer_scale_code,5,5);
cprintf("): %d\n",quantizer_scale_code);
}
#endif /* TRACE */
 
/* ISO/IEC 13818-2 section 7.4.2.2: Quantizer scale factor */
if (ld->MPEG2_Flag)
ld->quantizer_scale =
ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code]
: (quantizer_scale_code << 1);
else
ld->quantizer_scale = quantizer_scale_code;
 
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
/* make sure base.quantizer_scale is valid */
base.quantizer_scale = ld->quantizer_scale;
}
 
/* motion vectors */
 
 
/* ISO/IEC 13818-2 section 6.3.17.2: Motion vectors */
 
/* decode forward motion vectors */
if ((*macroblock_type & MACROBLOCK_MOTION_FORWARD)
|| ((*macroblock_type & MACROBLOCK_INTRA)
&& concealment_motion_vectors))
{
if (ld->MPEG2_Flag)
motion_vectors(PMV,dmvector,motion_vertical_field_select,
0,motion_vector_count,mv_format,f_code[0][0]-1,f_code[0][1]-1,
dmv,mvscale);
else
motion_vector(PMV[0][0],dmvector,
forward_f_code-1,forward_f_code-1,0,0,full_pel_forward_vector);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
/* decode backward motion vectors */
if (*macroblock_type & MACROBLOCK_MOTION_BACKWARD)
{
if (ld->MPEG2_Flag)
motion_vectors(PMV,dmvector,motion_vertical_field_select,
1,motion_vector_count,mv_format,f_code[1][0]-1,f_code[1][1]-1,0,
mvscale);
else
motion_vector(PMV[0][1],dmvector,
backward_f_code-1,backward_f_code-1,0,0,full_pel_backward_vector);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
if ((*macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
Flush_Buffer(1); /* remove marker_bit */
 
if (base.scalable_mode==SC_DP && base.priority_breakpoint==3)
ld = &enhan;
 
/* macroblock_pattern */
/* ISO/IEC 13818-2 section 6.3.17.4: Coded block pattern */
if (*macroblock_type & MACROBLOCK_PATTERN)
{
coded_block_pattern = Get_coded_block_pattern();
 
if (chroma_format==CHROMA422)
{
/* coded_block_pattern_1 */
coded_block_pattern = (coded_block_pattern<<2) | Get_Bits(2);
 
#ifdef TRACE
if (Trace_Flag)
{
cprintf("coded_block_pattern_1: ");
Print_Bits(coded_block_pattern,2,2);
cprintf(" (%d)\n",coded_block_pattern&3);
}
#endif /* TRACE */
}
else if (chroma_format==CHROMA444)
{
/* coded_block_pattern_2 */
coded_block_pattern = (coded_block_pattern<<6) | Get_Bits(6);
 
#ifdef TRACE
if (Trace_Flag)
{
cprintf("coded_block_pattern_2: ");
Print_Bits(coded_block_pattern,6,6);
cprintf(" (%d)\n",coded_block_pattern&63);
}
#endif /* TRACE */
}
}
else
coded_block_pattern = (*macroblock_type & MACROBLOCK_INTRA) ?
(1<<block_count)-1 : 0;
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
 
/* decode blocks */
for (comp=0; comp<block_count; comp++)
{
/* SCALABILITY: Data Partitioning */
if (base.scalable_mode==SC_DP)
ld = &base;
 
Clear_Block(comp);
 
if (coded_block_pattern & (1<<(block_count-1-comp)))
{
if (*macroblock_type & MACROBLOCK_INTRA)
{
if (ld->MPEG2_Flag)
Decode_MPEG2_Intra_Block(comp,dc_dct_pred);
else
Decode_MPEG1_Intra_Block(comp,dc_dct_pred);
}
else
{
if (ld->MPEG2_Flag)
Decode_MPEG2_Non_Intra_Block(comp);
else
Decode_MPEG1_Non_Intra_Block(comp);
}
 
if (Fault_Flag) return(0); /* trigger: go to next slice */
}
}
 
if(picture_coding_type==D_TYPE)
{
/* remove end_of_macroblock (always 1, prevents startcode emulation) */
/* ISO/IEC 11172-2 section 2.4.2.7 and 2.4.3.6 */
marker_bit("D picture end_of_macroblock bit");
}
 
/* reset intra_dc predictors */
/* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
if (!(*macroblock_type & MACROBLOCK_INTRA))
dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
 
/* reset motion vector predictors */
if ((*macroblock_type & MACROBLOCK_INTRA) && !concealment_motion_vectors)
{
/* intra mb without concealment motion vectors */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
}
 
/* special "No_MC" macroblock_type case */
/* ISO/IEC 13818-2 section 7.6.3.5: Prediction in P pictures */
if ((picture_coding_type==P_TYPE)
&& !(*macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_INTRA)))
{
/* non-intra mb without forward mv in a P picture */
/* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
 
/* derive motion_type */
/* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes, frame_motion_type */
if (picture_structure==FRAME_PICTURE)
*motion_type = MC_FRAME;
else
{
*motion_type = MC_FIELD;
/* predict from field of same parity */
motion_vertical_field_select[0][0] = (picture_structure==BOTTOM_FIELD);
}
}
 
if (*stwclass==4)
{
/* purely spatially predicted macroblock */
/* ISO/IEC 13818-2 section 7.7.5.1: Resetting motion vector predictions */
PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
}
 
/* successfully decoded macroblock */
return(1);
 
} /* decode_macroblock */
 
 
/advdemos/branches/advdemos/fsf/mpeg2/gethdr.c
0,0 → 1,1074
/* gethdr.c, header decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
 
 
/* private prototypes */
static void sequence_header _ANSI_ARGS_((void));
static void group_of_pictures_header _ANSI_ARGS_((void));
static void picture_header _ANSI_ARGS_((void));
static void extension_and_user_data _ANSI_ARGS_((void));
static void sequence_extension _ANSI_ARGS_((void));
static void sequence_display_extension _ANSI_ARGS_((void));
static void quant_matrix_extension _ANSI_ARGS_((void));
static void sequence_scalable_extension _ANSI_ARGS_((void));
static void picture_display_extension _ANSI_ARGS_((void));
static void picture_coding_extension _ANSI_ARGS_((void));
static void picture_spatial_scalable_extension _ANSI_ARGS_((void));
static void picture_temporal_scalable_extension _ANSI_ARGS_((void));
static int extra_bit_information _ANSI_ARGS_((void));
static void copyright_extension _ANSI_ARGS_((void));
static void user_data _ANSI_ARGS_((void));
static void user_data _ANSI_ARGS_((void));
 
 
 
 
/* introduced in September 1995 to assist spatial scalable decoding */
static void Update_Temporal_Reference_Tacking_Data _ANSI_ARGS_((void));
/* private variables */
static int Temporal_Reference_Base = 0;
static int True_Framenum_max = -1;
static int Temporal_Reference_GOP_Reset = 0;
 
#define RESERVED -1
static double frame_rate_Table[16] =
{
0.0,
((23.0*1000.0)/1001.0),
24.0,
25.0,
((30.0*1000.0)/1001.0),
30.0,
50.0,
((60.0*1000.0)/1001.0),
60.0,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED,
RESERVED
};
 
/*
* decode headers from one input stream
* until an End of Sequence or picture start code
* is found
*/
int Get_Hdr()
{
unsigned int code;
 
for (;;)
{
/* look for next_start_code */
next_start_code();
code = Get_Bits32();
switch (code)
{
case SEQUENCE_HEADER_CODE:
sequence_header();
break;
case GROUP_START_CODE:
group_of_pictures_header();
break;
case PICTURE_START_CODE:
picture_header();
return 1;
break;
case SEQUENCE_END_CODE:
return 0;
break;
default:
if (!Quiet_Flag)
cprintf("Unexpected next_start_code %08x (ignored)\n",code);
break;
}
}
}
 
 
/* align to start of next next_start_code */
 
void next_start_code()
{
/* byte align */
Flush_Buffer(ld->Incnt&7);
while (Show_Bits(24)!=0x01L)
Flush_Buffer(8);
}
 
 
/* decode sequence header */
 
static void sequence_header()
{
int i;
int pos;
 
pos = ld->Bitcnt;
horizontal_size = Get_Bits(12);
vertical_size = Get_Bits(12);
aspect_ratio_information = Get_Bits(4);
frame_rate_code = Get_Bits(4);
bit_rate_value = Get_Bits(18);
marker_bit("sequence_header()");
vbv_buffer_size = Get_Bits(10);
constrained_parameters_flag = Get_Bits(1);
 
if((ld->load_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
else
{
for (i=0; i<64; i++)
ld->intra_quantizer_matrix[i] = default_intra_quantizer_matrix[i];
}
 
if((ld->load_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->non_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
else
{
for (i=0; i<64; i++)
ld->non_intra_quantizer_matrix[i] = 16;
}
 
/* copy luminance to chrominance matrices */
for (i=0; i<64; i++)
{
ld->chroma_intra_quantizer_matrix[i] =
ld->intra_quantizer_matrix[i];
 
ld->chroma_non_intra_quantizer_matrix[i] =
ld->non_intra_quantizer_matrix[i];
}
 
#ifdef VERBOSE
if (Verbose_Flag > NO_LAYER)
{
cprintf("sequence header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag > SEQUENCE_LAYER)
{
cprintf(" horizontal_size=%d\n",horizontal_size);
cprintf(" vertical_size=%d\n",vertical_size);
cprintf(" aspect_ratio_information=%d\n",aspect_ratio_information);
cprintf(" frame_rate_code=%d",frame_rate_code);
cprintf(" bit_rate_value=%d\n",bit_rate_value);
cprintf(" vbv_buffer_size=%d\n",vbv_buffer_size);
cprintf(" constrained_parameters_flag=%d\n",constrained_parameters_flag);
cprintf(" load_intra_quantizer_matrix=%d\n",ld->load_intra_quantizer_matrix);
cprintf(" load_non_intra_quantizer_matrix=%d\n",ld->load_non_intra_quantizer_matrix);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_header++;
#endif /* VERIFY */
 
extension_and_user_data();
}
 
 
 
/* decode group of pictures header */
/* ISO/IEC 13818-2 section 6.2.2.6 */
static void group_of_pictures_header()
{
int pos;
 
if (ld == &base)
{
Temporal_Reference_Base = True_Framenum_max + 1; /* *CH* */
Temporal_Reference_GOP_Reset = 1;
}
pos = ld->Bitcnt;
drop_flag = Get_Bits(1);
hour = Get_Bits(5);
minute = Get_Bits(6);
marker_bit("group_of_pictures_header()");
sec = Get_Bits(6);
frame = Get_Bits(6);
closed_gop = Get_Bits(1);
broken_link = Get_Bits(1);
 
#ifdef VERBOSE
if (Verbose_Flag > NO_LAYER)
{
cprintf("group of pictures (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag > SEQUENCE_LAYER)
{
cprintf(" drop_flag=%d\n",drop_flag);
cprintf(" timecode %d:%02d:%02d:%02d\n",hour,minute,sec,frame);
cprintf(" closed_gop=%d\n",closed_gop);
cprintf(" broken_link=%d\n",broken_link);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_group_of_pictures_header++;
#endif /* VERIFY */
 
extension_and_user_data();
 
}
 
 
/* decode picture header */
 
/* ISO/IEC 13818-2 section 6.2.3 */
static void picture_header()
{
int pos;
int Extra_Information_Byte_Count;
 
/* unless later overwritten by picture_spatial_scalable_extension() */
ld->pict_scal = 0;
pos = ld->Bitcnt;
temporal_reference = Get_Bits(10);
picture_coding_type = Get_Bits(3);
vbv_delay = Get_Bits(16);
 
if (picture_coding_type==P_TYPE || picture_coding_type==B_TYPE)
{
full_pel_forward_vector = Get_Bits(1);
forward_f_code = Get_Bits(3);
}
if (picture_coding_type==B_TYPE)
{
full_pel_backward_vector = Get_Bits(1);
backward_f_code = Get_Bits(3);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("picture header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" temporal_reference=%d\n",temporal_reference);
cprintf(" picture_coding_type=%d\n",picture_coding_type);
cprintf(" vbv_delay=%d\n",vbv_delay);
if (picture_coding_type==P_TYPE || picture_coding_type==B_TYPE)
{
cprintf(" full_pel_forward_vector=%d\n",full_pel_forward_vector);
cprintf(" forward_f_code =%d\n",forward_f_code);
}
if (picture_coding_type==B_TYPE)
{
cprintf(" full_pel_backward_vector=%d\n",full_pel_backward_vector);
cprintf(" backward_f_code =%d\n",backward_f_code);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_header++;
#endif /* VERIFY */
 
Extra_Information_Byte_Count =
extra_bit_information();
extension_and_user_data();
 
/* update tracking information used to assist spatial scalability */
Update_Temporal_Reference_Tacking_Data();
}
 
/* decode slice header */
 
/* ISO/IEC 13818-2 section 6.2.4 */
int slice_header()
{
int slice_vertical_position_extension;
int quantizer_scale_code;
int pos;
int slice_picture_id_enable = 0;
int slice_picture_id = 0;
int extra_information_slice = 0;
 
pos = ld->Bitcnt;
 
slice_vertical_position_extension =
(ld->MPEG2_Flag && vertical_size>2800) ? Get_Bits(3) : 0;
 
if (ld->scalable_mode==SC_DP)
ld->priority_breakpoint = Get_Bits(7);
 
quantizer_scale_code = Get_Bits(5);
ld->quantizer_scale =
ld->MPEG2_Flag ? (ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] : quantizer_scale_code<<1) : quantizer_scale_code;
 
/* slice_id introduced in March 1995 as part of the video corridendum
(after the IS was drafted in November 1994) */
if (Get_Bits(1))
{
ld->intra_slice = Get_Bits(1);
 
slice_picture_id_enable = Get_Bits(1);
slice_picture_id = Get_Bits(6);
 
extra_information_slice = extra_bit_information();
}
else
ld->intra_slice = 0;
 
#ifdef VERBOSE
if (Verbose_Flag>PICTURE_LAYER)
{
cprintf("slice header (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SLICE_LAYER)
{
if (ld->MPEG2_Flag && vertical_size>2800)
cprintf(" slice_vertical_position_extension=%d\n",slice_vertical_position_extension);
if (ld->scalable_mode==SC_DP)
cprintf(" priority_breakpoint=%d\n",ld->priority_breakpoint);
 
cprintf(" quantizer_scale_code=%d\n",quantizer_scale_code);
 
cprintf(" slice_picture_id_enable = %d\n", slice_picture_id_enable);
 
if(slice_picture_id_enable)
cprintf(" slice_picture_id = %d\n", slice_picture_id);
 
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_slice_header++;
#endif /* VERIFY */
 
 
return slice_vertical_position_extension;
}
 
 
/* decode extension and user data */
/* ISO/IEC 13818-2 section 6.2.2.2 */
static void extension_and_user_data()
{
int code,ext_ID;
 
next_start_code();
 
while ((code = Show_Bits(32))==EXTENSION_START_CODE || code==USER_DATA_START_CODE)
{
if (code==EXTENSION_START_CODE)
{
Flush_Buffer32();
ext_ID = Get_Bits(4);
switch (ext_ID)
{
case SEQUENCE_EXTENSION_ID:
sequence_extension();
break;
case SEQUENCE_DISPLAY_EXTENSION_ID:
sequence_display_extension();
break;
case QUANT_MATRIX_EXTENSION_ID:
quant_matrix_extension();
break;
case SEQUENCE_SCALABLE_EXTENSION_ID:
sequence_scalable_extension();
break;
case PICTURE_DISPLAY_EXTENSION_ID:
picture_display_extension();
break;
case PICTURE_CODING_EXTENSION_ID:
picture_coding_extension();
break;
case PICTURE_SPATIAL_SCALABLE_EXTENSION_ID:
picture_spatial_scalable_extension();
break;
case PICTURE_TEMPORAL_SCALABLE_EXTENSION_ID:
picture_temporal_scalable_extension();
break;
case COPYRIGHT_EXTENSION_ID:
copyright_extension();
break;
default:
cprintf("reserved extension start code ID %d\n",ext_ID);
break;
}
next_start_code();
}
else
{
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
cprintf("user data\n");
#endif /* VERBOSE */
Flush_Buffer32();
user_data();
}
}
}
 
 
/* decode sequence extension */
 
/* ISO/IEC 13818-2 section 6.2.2.3 */
static void sequence_extension()
{
int horizontal_size_extension;
int vertical_size_extension;
int bit_rate_extension;
int vbv_buffer_size_extension;
 
/* derive bit position for trace */
#ifdef VERBOSE
pos = ld->Bitcnt;
#endif
 
ld->MPEG2_Flag = 1;
 
ld->scalable_mode = SC_NONE; /* unless overwritten by sequence_scalable_extension() */
layer_id = 0; /* unless overwritten by sequence_scalable_extension() */
profile_and_level_indication = Get_Bits(8);
progressive_sequence = Get_Bits(1);
chroma_format = Get_Bits(2);
horizontal_size_extension = Get_Bits(2);
vertical_size_extension = Get_Bits(2);
bit_rate_extension = Get_Bits(12);
marker_bit("sequence_extension");
vbv_buffer_size_extension = Get_Bits(8);
low_delay = Get_Bits(1);
frame_rate_extension_n = Get_Bits(2);
frame_rate_extension_d = Get_Bits(5);
 
frame_rate = frame_rate_Table[frame_rate_code] *
((frame_rate_extension_n+1)/(frame_rate_extension_d+1));
 
/* special case for 422 profile & level must be made */
if((profile_and_level_indication>>7) & 1)
{ /* escape bit of profile_and_level_indication set */
/* 4:2:2 Profile @ Main Level */
if((profile_and_level_indication&15)==5)
{
profile = PROFILE_422;
level = MAIN_LEVEL;
}
}
else
{
profile = profile_and_level_indication >> 4; /* Profile is upper nibble */
level = profile_and_level_indication & 0xF; /* Level is lower nibble */
}
horizontal_size = (horizontal_size_extension<<12) | (horizontal_size&0x0fff);
vertical_size = (vertical_size_extension<<12) | (vertical_size&0x0fff);
 
 
/* ISO/IEC 13818-2 does not define bit_rate_value to be composed of
* both the original bit_rate_value parsed in sequence_header() and
* the optional bit_rate_extension in sequence_extension_header().
* However, we use it for bitstream verification purposes.
*/
 
bit_rate_value += (bit_rate_extension << 18);
bit_rate = ((double) bit_rate_value) * 400.0;
vbv_buffer_size += (vbv_buffer_size_extension << 10);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("sequence extension (byte %d)\n",(pos>>3)-4);
 
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" profile_and_level_indication=%d\n",profile_and_level_indication);
 
if (profile_and_level_indication<128)
{
cprintf(" profile=%d, level=%d\n",profile,level);
}
 
cprintf(" progressive_sequence=%d\n",progressive_sequence);
cprintf(" chroma_format=%d\n",chroma_format);
cprintf(" horizontal_size_extension=%d\n",horizontal_size_extension);
cprintf(" vertical_size_extension=%d\n",vertical_size_extension);
cprintf(" bit_rate_extension=%d\n",bit_rate_extension);
cprintf(" vbv_buffer_size_extension=%d\n",vbv_buffer_size_extension);
cprintf(" low_delay=%d\n",low_delay);
cprintf(" frame_rate_extension_n=%d\n",frame_rate_extension_n);
cprintf(" frame_rate_extension_d=%d\n",frame_rate_extension_d);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_extension++;
#endif /* VERIFY */
 
 
}
 
 
/* decode sequence display extension */
 
static void sequence_display_extension()
{
int pos;
 
pos = ld->Bitcnt;
video_format = Get_Bits(3);
color_description = Get_Bits(1);
 
if (color_description)
{
color_primaries = Get_Bits(8);
transfer_characteristics = Get_Bits(8);
matrix_coefficients = Get_Bits(8);
}
 
display_horizontal_size = Get_Bits(14);
marker_bit("sequence_display_extension");
display_vertical_size = Get_Bits(14);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("sequence display extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
 
cprintf(" video_format=%d\n",video_format);
cprintf(" color_description=%d\n",color_description);
 
if (color_description)
{
cprintf(" color_primaries=%d\n",color_primaries);
cprintf(" transfer_characteristics=%d\n",transfer_characteristics);
cprintf(" matrix_coefficients=%d\n",matrix_coefficients);
}
cprintf(" display_horizontal_size=%d\n",display_horizontal_size);
cprintf(" display_vertical_size=%d\n",display_vertical_size);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_display_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode quant matrix entension */
/* ISO/IEC 13818-2 section 6.2.3.2 */
static void quant_matrix_extension()
{
int i;
int pos;
 
pos = ld->Bitcnt;
 
if((ld->load_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
{
ld->chroma_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= ld->intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= Get_Bits(8);
}
}
 
if((ld->load_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
{
ld->chroma_non_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= ld->non_intra_quantizer_matrix[scan[ZIG_ZAG][i]]
= Get_Bits(8);
}
}
 
if((ld->load_chroma_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->chroma_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
 
if((ld->load_chroma_non_intra_quantizer_matrix = Get_Bits(1)))
{
for (i=0; i<64; i++)
ld->chroma_non_intra_quantizer_matrix[scan[ZIG_ZAG][i]] = Get_Bits(8);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("quant matrix extension (byte %d)\n",(pos>>3)-4);
cprintf(" load_intra_quantizer_matrix=%d\n",
ld->load_intra_quantizer_matrix);
cprintf(" load_non_intra_quantizer_matrix=%d\n",
ld->load_non_intra_quantizer_matrix);
cprintf(" load_chroma_intra_quantizer_matrix=%d\n",
ld->load_chroma_intra_quantizer_matrix);
cprintf(" load_chroma_non_intra_quantizer_matrix=%d\n",
ld->load_chroma_non_intra_quantizer_matrix);
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_quant_matrix_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode sequence scalable extension */
/* ISO/IEC 13818-2 section 6.2.2.5 */
static void sequence_scalable_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
/* values (without the +1 offset) of scalable_mode are defined in
Table 6-10 of ISO/IEC 13818-2 */
ld->scalable_mode = Get_Bits(2) + 1; /* add 1 to make SC_DP != SC_NONE */
 
layer_id = Get_Bits(4);
 
if (ld->scalable_mode==SC_SPAT)
{
lower_layer_prediction_horizontal_size = Get_Bits(14);
marker_bit("sequence_scalable_extension()");
lower_layer_prediction_vertical_size = Get_Bits(14);
horizontal_subsampling_factor_m = Get_Bits(5);
horizontal_subsampling_factor_n = Get_Bits(5);
vertical_subsampling_factor_m = Get_Bits(5);
vertical_subsampling_factor_n = Get_Bits(5);
}
 
if (ld->scalable_mode==SC_TEMP)
Error("temporal scalability not implemented\n");
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("sequence scalable extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" scalable_mode=%d\n",ld->scalable_mode-1);
cprintf(" layer_id=%d\n",layer_id);
if (ld->scalable_mode==SC_SPAT)
{
cprintf(" lower_layer_prediction_horiontal_size=%d\n",
lower_layer_prediction_horizontal_size);
cprintf(" lower_layer_prediction_vertical_size=%d\n",
lower_layer_prediction_vertical_size);
cprintf(" horizontal_subsampling_factor_m=%d\n",
horizontal_subsampling_factor_m);
cprintf(" horizontal_subsampling_factor_n=%d\n",
horizontal_subsampling_factor_n);
cprintf(" vertical_subsampling_factor_m=%d\n",
vertical_subsampling_factor_m);
cprintf(" vertical_subsampling_factor_n=%d\n",
vertical_subsampling_factor_n);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_sequence_scalable_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture display extension */
/* ISO/IEC 13818-2 section 6.2.3.3. */
static void picture_display_extension()
{
int i;
int number_of_frame_center_offsets;
int pos;
 
pos = ld->Bitcnt;
/* based on ISO/IEC 13818-2 section 6.3.12
(November 1994) Picture display extensions */
 
/* derive number_of_frame_center_offsets */
if(progressive_sequence)
{
if(repeat_first_field)
{
if(top_field_first)
number_of_frame_center_offsets = 3;
else
number_of_frame_center_offsets = 2;
}
else
{
number_of_frame_center_offsets = 1;
}
}
else
{
if(picture_structure!=FRAME_PICTURE)
{
number_of_frame_center_offsets = 1;
}
else
{
if(repeat_first_field)
number_of_frame_center_offsets = 3;
else
number_of_frame_center_offsets = 2;
}
}
 
 
/* now parse */
for (i=0; i<number_of_frame_center_offsets; i++)
{
frame_center_horizontal_offset[i] = Get_Bits(16);
marker_bit("picture_display_extension, first marker bit");
frame_center_vertical_offset[i] = Get_Bits(16);
marker_bit("picture_display_extension, second marker bit");
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("picture display extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
 
for (i=0; i<number_of_frame_center_offsets; i++)
{
cprintf(" frame_center_horizontal_offset[%d]=%d\n",i,
frame_center_horizontal_offset[i]);
cprintf(" frame_center_vertical_offset[%d]=%d\n",i,
frame_center_vertical_offset[i]);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_display_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture coding extension */
static void picture_coding_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
f_code[0][0] = Get_Bits(4);
f_code[0][1] = Get_Bits(4);
f_code[1][0] = Get_Bits(4);
f_code[1][1] = Get_Bits(4);
 
intra_dc_precision = Get_Bits(2);
picture_structure = Get_Bits(2);
top_field_first = Get_Bits(1);
frame_pred_frame_dct = Get_Bits(1);
concealment_motion_vectors = Get_Bits(1);
ld->q_scale_type = Get_Bits(1);
intra_vlc_format = Get_Bits(1);
ld->alternate_scan = Get_Bits(1);
repeat_first_field = Get_Bits(1);
chroma_420_type = Get_Bits(1);
progressive_frame = Get_Bits(1);
composite_display_flag = Get_Bits(1);
 
if (composite_display_flag)
{
v_axis = Get_Bits(1);
field_sequence = Get_Bits(3);
sub_carrier = Get_Bits(1);
burst_amplitude = Get_Bits(7);
sub_carrier_phase = Get_Bits(8);
}
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("picture coding extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" forward horizontal f_code=%d\n", f_code[0][0]);
cprintf(" forward vertical f_code=%d\n", f_code[0][1]);
cprintf(" backward horizontal f_code=%d\n", f_code[1][0]);
cprintf(" backward_vertical f_code=%d\n", f_code[1][1]);
cprintf(" intra_dc_precision=%d\n",intra_dc_precision);
cprintf(" picture_structure=%d\n",picture_structure);
cprintf(" top_field_first=%d\n",top_field_first);
cprintf(" frame_pred_frame_dct=%d\n",frame_pred_frame_dct);
cprintf(" concealment_motion_vectors=%d\n",concealment_motion_vectors);
cprintf(" q_scale_type=%d\n",ld->q_scale_type);
cprintf(" intra_vlc_format=%d\n",intra_vlc_format);
cprintf(" alternate_scan=%d\n",ld->alternate_scan);
cprintf(" repeat_first_field=%d\n",repeat_first_field);
cprintf(" chroma_420_type=%d\n",chroma_420_type);
cprintf(" progressive_frame=%d\n",progressive_frame);
cprintf(" composite_display_flag=%d\n",composite_display_flag);
 
if (composite_display_flag)
{
cprintf(" v_axis=%d\n",v_axis);
cprintf(" field_sequence=%d\n",field_sequence);
cprintf(" sub_carrier=%d\n",sub_carrier);
cprintf(" burst_amplitude=%d\n",burst_amplitude);
cprintf(" sub_carrier_phase=%d\n",sub_carrier_phase);
}
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_coding_extension++;
#endif /* VERIFY */
}
 
 
/* decode picture spatial scalable extension */
/* ISO/IEC 13818-2 section 6.2.3.5. */
static void picture_spatial_scalable_extension()
{
int pos;
 
pos = ld->Bitcnt;
 
ld->pict_scal = 1; /* use spatial scalability in this picture */
 
lower_layer_temporal_reference = Get_Bits(10);
marker_bit("picture_spatial_scalable_extension(), first marker bit");
lower_layer_horizontal_offset = Get_Bits(15);
if (lower_layer_horizontal_offset>=16384)
lower_layer_horizontal_offset-= 32768;
marker_bit("picture_spatial_scalable_extension(), second marker bit");
lower_layer_vertical_offset = Get_Bits(15);
if (lower_layer_vertical_offset>=16384)
lower_layer_vertical_offset-= 32768;
spatial_temporal_weight_code_table_index = Get_Bits(2);
lower_layer_progressive_frame = Get_Bits(1);
lower_layer_deinterlaced_field_select = Get_Bits(1);
 
#ifdef VERBOSE
if (Verbose_Flag>NO_LAYER)
{
cprintf("picture spatial scalable extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" lower_layer_temporal_reference=%d\n",lower_layer_temporal_reference);
cprintf(" lower_layer_horizontal_offset=%d\n",lower_layer_horizontal_offset);
cprintf(" lower_layer_vertical_offset=%d\n",lower_layer_vertical_offset);
cprintf(" spatial_temporal_weight_code_table_index=%d\n",
spatial_temporal_weight_code_table_index);
cprintf(" lower_layer_progressive_frame=%d\n",lower_layer_progressive_frame);
cprintf(" lower_layer_deinterlaced_field_select=%d\n",lower_layer_deinterlaced_field_select);
}
}
#endif /* VERBOSE */
 
#ifdef VERIFY
verify_picture_spatial_scalable_extension++;
#endif /* VERIFY */
 
}
 
 
/* decode picture temporal scalable extension
*
* not implemented
*/
/* ISO/IEC 13818-2 section 6.2.3.4. */
static void picture_temporal_scalable_extension()
{
Error("temporal scalability not supported\n");
 
#ifdef VERIFY
verify_picture_temporal_scalable_extension++;
#endif /* VERIFY */
}
 
 
/* decode extra bit information */
/* ISO/IEC 13818-2 section 6.2.3.4. */
static int extra_bit_information()
{
int Byte_Count = 0;
 
while (Get_Bits1())
{
Flush_Buffer(8);
Byte_Count++;
}
 
return(Byte_Count);
}
 
 
 
/* ISO/IEC 13818-2 section 5.3 */
/* Purpose: this function is mainly designed to aid in bitstream conformance
testing. A simple Flush_Buffer(1) would do */
void marker_bit(text)
char *text;
{
int marker;
 
marker = Get_Bits(1);
 
#ifdef VERIFY
if(!marker)
cprintf("ERROR: %s--marker_bit set to 0",text);
#endif
}
 
 
/* ISO/IEC 13818-2 sections 6.3.4.1 and 6.2.2.2.2 */
static void user_data()
{
/* skip ahead to the next start code */
next_start_code();
}
 
 
 
/* Copyright extension */
/* ISO/IEC 13818-2 section 6.2.3.6. */
/* (header added in November, 1994 to the IS document) */
 
 
static void copyright_extension()
{
int pos;
int reserved_data;
 
pos = ld->Bitcnt;
 
copyright_flag = Get_Bits(1);
copyright_identifier = Get_Bits(8);
original_or_copy = Get_Bits(1);
/* reserved */
reserved_data = Get_Bits(7);
 
marker_bit("copyright_extension(), first marker bit");
copyright_number_1 = Get_Bits(20);
marker_bit("copyright_extension(), second marker bit");
copyright_number_2 = Get_Bits(22);
marker_bit("copyright_extension(), third marker bit");
copyright_number_3 = Get_Bits(22);
 
if(Verbose_Flag>NO_LAYER)
{
cprintf("copyright_extension (byte %d)\n",(pos>>3)-4);
if (Verbose_Flag>SEQUENCE_LAYER)
{
cprintf(" copyright_flag =%d\n",copyright_flag);
cprintf(" copyright_identifier=%d\n",copyright_identifier);
cprintf(" original_or_copy = %d (original=1, copy=0)\n",
original_or_copy);
cprintf(" copyright_number_1=%d\n",copyright_number_1);
cprintf(" copyright_number_2=%d\n",copyright_number_2);
cprintf(" copyright_number_3=%d\n",copyright_number_3);
}
}
 
#ifdef VERIFY
verify_copyright_extension++;
#endif /* VERIFY */
}
 
 
 
/* introduced in September 1995 to assist Spatial Scalability */
static void Update_Temporal_Reference_Tacking_Data()
{
static int temporal_reference_wrap = 0;
static int temporal_reference_old = 0;
 
if (ld == &base) /* *CH* */
{
if (picture_coding_type!=B_TYPE && temporal_reference!=temporal_reference_old)
/* check first field of */
{
/* non-B-frame */
if (temporal_reference_wrap)
{/* wrap occured at previous I- or P-frame */
/* now all intervening B-frames which could
still have high temporal_reference values are done */
Temporal_Reference_Base += 1024;
temporal_reference_wrap = 0;
}
/* distinguish from a reset */
if (temporal_reference<temporal_reference_old && !Temporal_Reference_GOP_Reset)
temporal_reference_wrap = 1; /* we must have just passed a GOP-Header! */
temporal_reference_old = temporal_reference;
Temporal_Reference_GOP_Reset = 0;
}
 
True_Framenum = Temporal_Reference_Base + temporal_reference;
/* temporary wrap of TR at 1024 for M frames */
if (temporal_reference_wrap && temporal_reference <= temporal_reference_old)
True_Framenum += 1024;
 
True_Framenum_max = (True_Framenum > True_Framenum_max) ?
True_Framenum : True_Framenum_max;
}
}
/advdemos/branches/advdemos/fsf/mpeg2/gvideo.c
0,0 → 1,51
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
#include "drivers/glib.h"
 
#include "fsf_contract.h"
 
#include "config.h"
#include "global.h"
 
extern void *start_file;
extern void *end_file;
 
int Init_Mpeg_Decoder(void *start,void *end);
int Decode_Bitstream();
 
void *mpeg2decoder(void *arg)
{
int init = 1;
Init_Mpeg_Decoder(start_file,end_file);
while(1) {
if (init == 1) {
Decode_Bitstream();
}
 
}
return 0;
 
}
 
 
/advdemos/branches/advdemos/fsf/mpeg2/idctref.c
0,0 → 1,108
/* Reference_IDCT.c, Inverse Discrete Fourier Transform, double precision */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* Perform IEEE 1180 reference (64-bit floating point, separable 8x1
* direct matrix multiply) Inverse Discrete Cosine Transform
*/
 
 
/* Here we use math.h to generate constants. Compiler results may
vary a little */
 
#include <math.h>
 
#include "config.h"
 
#ifndef PI
# ifdef M_PI
# define PI M_PI
# else
# define PI 3.14159265358979323846
# endif
#endif
 
/* global declarations */
void Initialize_Fast_IDCTref _ANSI_ARGS_((void));
void Reference_IDCT _ANSI_ARGS_((short *block));
 
/* private data */
 
/* cosine transform matrix for 8x1 IDCT */
static double c[8][8];
 
/* initialize DCT coefficient matrix */
 
void Initialize_Reference_IDCT()
{
int freq, time;
double scale;
 
for (freq=0; freq < 8; freq++)
{
scale = (freq == 0) ? sqrt(0.125) : 0.5;
for (time=0; time<8; time++)
c[freq][time] = scale*cos((PI/8.0)*freq*(time + 0.5));
}
}
 
/* perform IDCT matrix multiply for 8x8 coefficient block */
 
void Reference_IDCT(block)
short *block;
{
int i, j, k, v;
double partial_product;
double tmp[64];
 
for (i=0; i<8; i++)
for (j=0; j<8; j++)
{
partial_product = 0.0;
 
for (k=0; k<8; k++)
partial_product+= c[k][j]*block[8*i+k];
 
tmp[8*i+j] = partial_product;
}
 
/* Transpose operation is integrated into address mapping by switching
loop order of i and j */
 
for (j=0; j<8; j++)
for (i=0; i<8; i++)
{
partial_product = 0.0;
 
for (k=0; k<8; k++)
partial_product+= c[k][i]*tmp[8*k+j];
 
v = (int) floor(partial_product+0.5);
block[8*i+j] = (v<-256) ? -256 : ((v>255) ? 255 : v);
}
}
/advdemos/branches/advdemos/fsf/mpeg2/idct.c
0,0 → 1,211
/* idct.c, inverse fast discrete cosine transform */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/**********************************************************/
/* inverse two dimensional DCT, Chen-Wang algorithm */
/* (cf. IEEE ASSP-32, pp. 803-816, Aug. 1984) */
/* 32-bit integer arithmetic (8 bit coefficients) */
/* 11 mults, 29 adds per DCT */
/* sE, 18.8.91 */
/**********************************************************/
/* coefficients extended to 12 bit for IEEE1180-1990 */
/* compliance sE, 2.1.94 */
/**********************************************************/
 
/* this code assumes >> to be a two's-complement arithmetic */
/* right shift: (-2)>>1 == -1 , (-3)>>1 == -2 */
 
#include "config.h"
 
#define W1 2841 /* 2048*sqrt(2)*cos(1*pi/16) */
#define W2 2676 /* 2048*sqrt(2)*cos(2*pi/16) */
#define W3 2408 /* 2048*sqrt(2)*cos(3*pi/16) */
#define W5 1609 /* 2048*sqrt(2)*cos(5*pi/16) */
#define W6 1108 /* 2048*sqrt(2)*cos(6*pi/16) */
#define W7 565 /* 2048*sqrt(2)*cos(7*pi/16) */
 
/* global declarations */
void Initialize_Fast_IDCT _ANSI_ARGS_((void));
void Fast_IDCT _ANSI_ARGS_((short *block));
 
/* private data */
static short iclip[1024]; /* clipping table */
static short *iclp;
 
/* private prototypes */
static void idctrow _ANSI_ARGS_((short *blk));
static void idctcol _ANSI_ARGS_((short *blk));
 
/* row (horizontal) IDCT
*
* 7 pi 1
* dst[k] = sum c[l] * src[l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 128
* c[1..7] = 128*sqrt(2)
*/
 
static void idctrow(blk)
short *blk;
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
 
/* shortcut */
if (!((x1 = blk[4]<<11) | (x2 = blk[6]) | (x3 = blk[2]) |
(x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3])))
{
blk[0]=blk[1]=blk[2]=blk[3]=blk[4]=blk[5]=blk[6]=blk[7]=blk[0]<<3;
return;
}
 
x0 = (blk[0]<<11) + 128; /* for proper rounding in the fourth stage */
 
/* first stage */
x8 = W7*(x4+x5);
x4 = x8 + (W1-W7)*x4;
x5 = x8 - (W1+W7)*x5;
x8 = W3*(x6+x7);
x6 = x8 - (W3-W5)*x6;
x7 = x8 - (W3+W5)*x7;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2);
x2 = x1 - (W2+W6)*x2;
x3 = x1 + (W2-W6)*x3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[0] = (x7+x1)>>8;
blk[1] = (x3+x2)>>8;
blk[2] = (x0+x4)>>8;
blk[3] = (x8+x6)>>8;
blk[4] = (x8-x6)>>8;
blk[5] = (x0-x4)>>8;
blk[6] = (x3-x2)>>8;
blk[7] = (x7-x1)>>8;
}
 
/* column (vertical) IDCT
*
* 7 pi 1
* dst[8*k] = sum c[l] * src[8*l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 1/1024
* c[1..7] = (1/1024)*sqrt(2)
*/
static void idctcol(blk)
short *blk;
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
 
/* shortcut */
if (!((x1 = (blk[8*4]<<8)) | (x2 = blk[8*6]) | (x3 = blk[8*2]) |
(x4 = blk[8*1]) | (x5 = blk[8*7]) | (x6 = blk[8*5]) | (x7 = blk[8*3])))
{
blk[8*0]=blk[8*1]=blk[8*2]=blk[8*3]=blk[8*4]=blk[8*5]=blk[8*6]=blk[8*7]=
iclp[(blk[8*0]+32)>>6];
return;
}
 
x0 = (blk[8*0]<<8) + 8192;
 
/* first stage */
x8 = W7*(x4+x5) + 4;
x4 = (x8+(W1-W7)*x4)>>3;
x5 = (x8-(W1+W7)*x5)>>3;
x8 = W3*(x6+x7) + 4;
x6 = (x8-(W3-W5)*x6)>>3;
x7 = (x8-(W3+W5)*x7)>>3;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2) + 4;
x2 = (x1-(W2+W6)*x2)>>3;
x3 = (x1+(W2-W6)*x3)>>3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[8*0] = iclp[(x7+x1)>>14];
blk[8*1] = iclp[(x3+x2)>>14];
blk[8*2] = iclp[(x0+x4)>>14];
blk[8*3] = iclp[(x8+x6)>>14];
blk[8*4] = iclp[(x8-x6)>>14];
blk[8*5] = iclp[(x0-x4)>>14];
blk[8*6] = iclp[(x3-x2)>>14];
blk[8*7] = iclp[(x7-x1)>>14];
}
 
/* two dimensional inverse discrete cosine transform */
void Fast_IDCT(block)
short *block;
{
int i;
 
for (i=0; i<8; i++)
idctrow(block+8*i);
 
for (i=0; i<8; i++)
idctcol(block+i);
}
 
void Initialize_Fast_IDCT()
{
int i;
 
iclp = iclip+512;
for (i= -512; i<512; i++)
iclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i);
}
/advdemos/branches/advdemos/fsf/mpeg2/getvlc.c
0,0 → 1,797
/* getvlc.c, variable length decoding */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "config.h"
#include "global.h"
#include "getvlc.h"
 
/* private prototypes */
/* generic picture macroblock type processing functions */
static int Get_I_macroblock_type _ANSI_ARGS_((void));
static int Get_P_macroblock_type _ANSI_ARGS_((void));
static int Get_B_macroblock_type _ANSI_ARGS_((void));
static int Get_D_macroblock_type _ANSI_ARGS_((void));
 
/* spatial picture macroblock type processing functions */
static int Get_I_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_P_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_B_Spatial_macroblock_type _ANSI_ARGS_((void));
static int Get_SNR_macroblock_type _ANSI_ARGS_((void));
 
int Get_macroblock_type()
{
int macroblock_type = 0;
 
if (ld->scalable_mode==SC_SNR)
macroblock_type = Get_SNR_macroblock_type();
else
{
switch (picture_coding_type)
{
case I_TYPE:
macroblock_type = ld->pict_scal ? Get_I_Spatial_macroblock_type() : Get_I_macroblock_type();
break;
case P_TYPE:
macroblock_type = ld->pict_scal ? Get_P_Spatial_macroblock_type() : Get_P_macroblock_type();
break;
case B_TYPE:
macroblock_type = ld->pict_scal ? Get_B_Spatial_macroblock_type() : Get_B_macroblock_type();
break;
case D_TYPE:
macroblock_type = Get_D_macroblock_type();
break;
default:
cprintf("Get_macroblock_type(): unrecognized picture coding type\n");
break;
}
}
 
return macroblock_type;
}
 
static int Get_I_macroblock_type()
{
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(I) ");
#endif /* TRACE */
 
if (Get_Bits1())
{
#ifdef TRACE
if (Trace_Flag)
cprintf("(1): Intra (1)\n");
#endif /* TRACE */
return 1;
}
 
if (!Get_Bits1())
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
}
 
#ifdef TRACE
if (Trace_Flag)
cprintf("(01): Intra, Quant (17)\n");
#endif /* TRACE */
 
return 17;
}
 
static char *MBdescr[]={
"", "Intra", "No MC, Coded", "",
"Bwd, Not Coded", "", "Bwd, Coded", "",
"Fwd, Not Coded", "", "Fwd, Coded", "",
"Interp, Not Coded", "", "Interp, Coded", "",
"", "Intra, Quant", "No MC, Coded, Quant", "",
"", "", "Bwd, Coded, Quant", "",
"", "", "Fwd, Coded, Quant", "",
"", "", "Interp, Coded, Quant", ""
};
 
static int Get_P_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(P) (");
#endif /* TRACE */
 
if ((code = Show_Bits(6))>=8)
{
code >>= 3;
Flush_Buffer(PMBtab0[code].len);
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,3,PMBtab0[code].len);
cprintf("): %s (%d)\n",MBdescr[(int)PMBtab0[code].val],PMBtab0[code].val);
}
#endif /* TRACE */
return PMBtab0[code].val;
}
 
if (code==0)
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(PMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,PMBtab1[code].len);
cprintf("): %s (%d)\n",MBdescr[(int)PMBtab1[code].val],PMBtab1[code].val);
}
#endif /* TRACE */
 
return PMBtab1[code].val;
}
 
static int Get_B_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(B) (");
#endif /* TRACE */
 
if ((code = Show_Bits(6))>=8)
{
code >>= 2;
Flush_Buffer(BMBtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,BMBtab0[code].len);
cprintf("): %s (%d)\n",MBdescr[(int)BMBtab0[code].val],BMBtab0[code].val);
}
#endif /* TRACE */
 
return BMBtab0[code].val;
}
 
if (code==0)
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(BMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,BMBtab1[code].len);
cprintf("): %s (%d)\n",MBdescr[(int)BMBtab1[code].val],BMBtab1[code].val);
}
#endif /* TRACE */
 
return BMBtab1[code].val;
}
 
static int Get_D_macroblock_type()
{
if (!Get_Bits1())
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag=1;
}
 
return 1;
}
 
/* macroblock_type for pictures with spatial scalability */
static int Get_I_Spatial_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(I,spat) (");
#endif /* TRACE */
 
code = Show_Bits(4);
 
if (code==0)
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,spIMBtab[code].len);
cprintf("): %02x\n",spIMBtab[code].val);
}
#endif /* TRACE */
 
Flush_Buffer(spIMBtab[code].len);
return spIMBtab[code].val;
}
 
static int Get_P_Spatial_macroblock_type()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(P,spat) (");
#endif /* TRACE */
 
code = Show_Bits(7);
 
if (code<2)
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
if (code>=16)
{
code >>= 3;
Flush_Buffer(spPMBtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,4,spPMBtab0[code].len);
cprintf("): %02x\n",spPMBtab0[code].val);
}
#endif /* TRACE */
 
return spPMBtab0[code].val;
}
 
Flush_Buffer(spPMBtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,7,spPMBtab1[code].len);
cprintf("): %02x\n",spPMBtab1[code].val);
}
#endif /* TRACE */
 
return spPMBtab1[code].val;
}
 
static int Get_B_Spatial_macroblock_type()
{
int code;
VLCtab *p;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_type(B,spat) (");
#endif /* TRACE */
 
code = Show_Bits(9);
 
if (code>=64)
p = &spBMBtab0[(code>>5)-2];
else if (code>=16)
p = &spBMBtab1[(code>>2)-4];
else if (code>=8)
p = &spBMBtab2[code-8];
else
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(p->len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,9,p->len);
printf("): %02x\n",p->val);
}
#endif /* TRACE */
 
return p->val;
}
 
static int Get_SNR_macroblock_type()
{
int code;
 
#ifdef TRACE /* *CH* */
if (Trace_Flag)
cprintf("macroblock_type(SNR) (");
#endif
 
code = Show_Bits(3);
 
if (code==0)
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_type code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(SNRMBtab[code].len);
 
#ifdef TRACE /* *CH* */
if (Trace_Flag)
{
Print_Bits(code,3,SNRMBtab[code].len);
cprintf("): %s (%d)\n",MBdescr[(int)SNRMBtab[code].val],SNRMBtab[code].val);
}
#endif
 
 
return SNRMBtab[code].val;
}
 
int Get_motion_code()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("motion_code (");
#endif /* TRACE */
 
if (Get_Bits1())
{
#ifdef TRACE
if (Trace_Flag)
cprintf("0): 0\n");
#endif /* TRACE */
return 0;
}
 
if ((code = Show_Bits(9))>=64)
{
code >>= 6;
Flush_Buffer(MVtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,3,MVtab0[code].len);
cprintf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab0[code].val:MVtab0[code].val);
}
#endif /* TRACE */
 
return Get_Bits1()?-MVtab0[code].val:MVtab0[code].val;
}
 
if (code>=24)
{
code >>= 3;
Flush_Buffer(MVtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,6,MVtab1[code].len);
cprintf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab1[code].val:MVtab1[code].val);
}
#endif /* TRACE */
 
return Get_Bits1()?-MVtab1[code].val:MVtab1[code].val;
}
 
if ((code-=12)<0)
{
if (!Quiet_Flag)
/* HACK */
cprintf("Invalid motion_vector code (MBA %d, pic %d)\n", global_MBA, global_pic);
Fault_Flag=1;
return 0;
}
 
Flush_Buffer(MVtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code+12,9,MVtab2[code].len);
cprintf("%d): %d\n",
Show_Bits(1),Show_Bits(1)?-MVtab2[code].val:MVtab2[code].val);
}
#endif /* TRACE */
 
return Get_Bits1() ? -MVtab2[code].val : MVtab2[code].val;
}
 
/* get differential motion vector (for dual prime prediction) */
int Get_dmvector()
{
#ifdef TRACE
if (Trace_Flag)
cprintf("dmvector (");
#endif /* TRACE */
 
if (Get_Bits(1))
{
#ifdef TRACE
if (Trace_Flag)
cprintf(Show_Bits(1) ? "11): -1\n" : "10): 1\n");
#endif /* TRACE */
return Get_Bits(1) ? -1 : 1;
}
else
{
#ifdef TRACE
if (Trace_Flag)
cprintf("0): 0\n");
#endif /* TRACE */
return 0;
}
}
 
int Get_coded_block_pattern()
{
int code;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("coded_block_pattern_420 (");
#endif /* TRACE */
 
if ((code = Show_Bits(9))>=128)
{
code >>= 4;
Flush_Buffer(CBPtab0[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,5,CBPtab0[code].len);
cprintf("): ");
Print_Bits(CBPtab0[code].val,6,6);
cprintf(" (%d)\n",CBPtab0[code].val);
}
#endif /* TRACE */
 
return CBPtab0[code].val;
}
 
if (code>=8)
{
code >>= 1;
Flush_Buffer(CBPtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,8,CBPtab1[code].len);
cprintf("): ");
Print_Bits(CBPtab1[code].val,6,6);
cprintf(" (%d)\n",CBPtab1[code].val);
}
#endif /* TRACE */
 
return CBPtab1[code].val;
}
 
if (code<1)
{
if (!Quiet_Flag)
cprintf("Invalid coded_block_pattern code\n");
Fault_Flag = 1;
return 0;
}
 
Flush_Buffer(CBPtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,9,CBPtab2[code].len);
cprintf("): ");
Print_Bits(CBPtab2[code].val,6,6);
cprintf(" (%d)\n",CBPtab2[code].val);
}
#endif /* TRACE */
 
return CBPtab2[code].val;
}
 
int Get_macroblock_address_increment()
{
int code, val;
 
#ifdef TRACE
if (Trace_Flag)
cprintf("macroblock_address_increment (");
#endif /* TRACE */
 
val = 0;
 
while ((code = Show_Bits(11))<24)
{
if (code!=15) /* if not macroblock_stuffing */
{
if (code==8) /* if macroblock_escape */
{
#ifdef TRACE
if (Trace_Flag)
cprintf("00000001000 ");
#endif /* TRACE */
 
val+= 33;
}
else
{
if (!Quiet_Flag)
cprintf("Invalid macroblock_address_increment code\n");
 
Fault_Flag = 1;
return 1;
}
}
else /* macroblock suffing */
{
#ifdef TRACE
if (Trace_Flag)
cprintf("00000001111 ");
#endif /* TRACE */
}
 
Flush_Buffer(11);
}
 
/* macroblock_address_increment == 1 */
/* ('1' is in the MSB position of the lookahead) */
if (code>=1024)
{
Flush_Buffer(1);
#ifdef TRACE
if (Trace_Flag)
cprintf("1): %d\n",val+1);
#endif /* TRACE */
return val + 1;
}
 
/* codes 00010 ... 011xx */
if (code>=128)
{
/* remove leading zeros */
code >>= 6;
Flush_Buffer(MBAtab1[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code,5,MBAtab1[code].len);
printf("): %d\n",val+MBAtab1[code].val);
}
#endif /* TRACE */
 
return val + MBAtab1[code].val;
}
/* codes 00000011000 ... 0000111xxxx */
code-= 24; /* remove common base */
Flush_Buffer(MBAtab2[code].len);
 
#ifdef TRACE
if (Trace_Flag)
{
Print_Bits(code+24,11,MBAtab2[code].len);
cprintf("): %d\n",val+MBAtab2[code].val);
}
#endif /* TRACE */
 
return val + MBAtab2[code].val;
}
 
/* combined MPEG-1 and MPEG-2 stage. parse VLC and
perform dct_diff arithmetic.
 
MPEG-1: ISO/IEC 11172-2 section
MPEG-2: ISO/IEC 13818-2 section 7.2.1
Note: the arithmetic here is presented more elegantly than
the spec, yet the results, dct_diff, are the same.
*/
 
int Get_Luma_DC_dct_diff()
{
int code, size, dct_diff;
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("dct_dc_size_luminance: (");
*/
#endif /* TRACE */
 
/* decode length */
code = Show_Bits(5);
 
if (code<31)
{
size = DClumtab0[code].val;
Flush_Buffer(DClumtab0[code].len);
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code,5,DClumtab0[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
else
{
code = Show_Bits(9) - 0x1f0;
size = DClumtab1[code].val;
Flush_Buffer(DClumtab1[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code+0x1f0,9,DClumtab1[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf(", dct_dc_differential (");
*/
#endif /* TRACE */
 
if (size==0)
dct_diff = 0;
else
{
dct_diff = Get_Bits(size);
#ifdef TRACE
/*
if (Trace_Flag)
Print_Bits(dct_diff,size,size);
*/
#endif /* TRACE */
if ((dct_diff & (1<<(size-1)))==0)
dct_diff-= (1<<size) - 1;
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("): %d\n",dct_diff);
*/
#endif /* TRACE */
 
return dct_diff;
}
 
 
int Get_Chroma_DC_dct_diff()
{
int code, size, dct_diff;
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("dct_dc_size_chrominance: (");
*/
#endif /* TRACE */
 
/* decode length */
code = Show_Bits(5);
 
if (code<31)
{
size = DCchromtab0[code].val;
Flush_Buffer(DCchromtab0[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code,5,DCchromtab0[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
else
{
code = Show_Bits(10) - 0x3e0;
size = DCchromtab1[code].val;
Flush_Buffer(DCchromtab1[code].len);
 
#ifdef TRACE
/*
if (Trace_Flag)
{
Print_Bits(code+0x3e0,10,DCchromtab1[code].len);
printf("): %d",size);
}
*/
#endif /* TRACE */
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf(", dct_dc_differential (");
*/
#endif /* TRACE */
 
if (size==0)
dct_diff = 0;
else
{
dct_diff = Get_Bits(size);
#ifdef TRACE
/*
if (Trace_Flag)
Print_Bits(dct_diff,size,size);
*/
#endif /* TRACE */
if ((dct_diff & (1<<(size-1)))==0)
dct_diff-= (1<<size) - 1;
}
 
#ifdef TRACE
/*
if (Trace_Flag)
printf("): %d\n",dct_diff);
*/
#endif /* TRACE */
 
return dct_diff;
}
/advdemos/branches/advdemos/fsf/mpeg2/mpeg2dec.c
0,0 → 1,495
 
/* mpeg2dec.c, main(), initialization, option processing */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include "stdlib.h"
#include "drivers/glib.h"
 
#include "fsf_contract.h"
 
#define GLOBAL
#include "config.h"
#include "global.h"
 
/* private prototypes */
static int video_sequence _ANSI_ARGS_((int *framenum));
static int Headers _ANSI_ARGS_((void));
static void Initialize_Sequence _ANSI_ARGS_((void));
static void Initialize_Decoder _ANSI_ARGS_((void));
static void Deinitialize_Sequence _ANSI_ARGS_((void));
 
/* #define DEBUG */
 
static void Clear_Options();
#ifdef DEBUG
static void Print_Options();
#endif
 
#define MAX_M_QOS 0
#define MIN_M_QOS 0
 
int dos_video_preload(char *file_name, long max_size, void **start, void **end)
{
DOS_FILE* file;
void *buf;
long rd;
 
file = DOS_fopen(file_name,"r");
if (file == NULL) return -1;
 
buf = malloc(max_size);
*start = buf;
 
while(((rd = DOS_fread(buf, sizeof(BYTE), 2048, file)) == 2048) &&
((buf - *start + rd) < (max_size-2048))) {
buf += rd;
}
*end = buf + rd;
DOS_fclose(file);
return(0);
 
}
 
int Init_Mpeg_Decoder(void *start, void *end)
{
int code;
Clear_Options();
 
#ifdef DEBUG
Print_Options();
#endif
 
ld = &base; /* select base layer context */
ld->start_file_ptr = start;
ld->end_file_ptr = end;
ld->actual_file_ptr = ld->start_file_ptr;
 
/* open MPEG base layer bitstream file(s) */
/* NOTE: this is either a base layer stream or a spatial enhancement stream */
if ((base.Infile=1)<0)
{
cprintf("Base layer input file %s not found\n", Main_Bitstream_Filename);
}
 
 
if(base.Infile != 0)
{
Initialize_Buffer();
if(Show_Bits(8)==0x47)
{
sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
Error(Error_Text);
}
 
next_start_code();
code = Show_Bits(32);
 
switch(code)
{
case SEQUENCE_HEADER_CODE:
break;
case PACK_START_CODE:
System_Stream_Flag = 1;
case VIDEO_ELEMENTARY_STREAM:
System_Stream_Flag = 1;
break;
default:
sprintf(Error_Text,"Unable to recognize stream type\n");
Error(Error_Text);
break;
}
 
ld->actual_file_ptr = ld->start_file_ptr;
Initialize_Buffer();
}
 
if(base.Infile!=0)
{
ld->actual_file_ptr = ld->start_file_ptr;
}
 
Initialize_Buffer();
 
if(Two_Streams)
{
ld = &enhan; /* select enhancement layer context */
 
if ((enhan.Infile = 1)<0)
{
sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
Enhancement_Layer_Bitstream_Filename);
 
Error(Error_Text);
}
 
Initialize_Buffer();
ld = &base;
}
 
Initialize_Decoder();
 
//Decode_Bitstream();
 
return 0;
}
 
/* IMPLEMENTAION specific rouintes */
static void Initialize_Decoder()
{
int i;
 
/* Clip table */
if (!(Clip=(unsigned char *)malloc(1024)))
Error("Clip[] malloc failed\n");
 
Clip += 384;
 
for (i=-384; i<640; i++)
Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
 
/* IDCT */
if (Reference_IDCT_Flag)
Initialize_Reference_IDCT();
else
Initialize_Fast_IDCT();
 
}
 
/* mostly IMPLEMENTAION specific rouintes */
static void Initialize_Sequence()
{
int cc, size;
static int Table_6_20[3] = {6,8,12};
 
/* check scalability mode of enhancement layer */
if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
Error("unsupported scalability mode\n");
 
/* force MPEG-1 parameters for proper decoder behavior */
/* see ISO/IEC 13818-2 section D.9.14 */
if (!base.MPEG2_Flag)
{
progressive_sequence = 1;
progressive_frame = 1;
picture_structure = FRAME_PICTURE;
frame_pred_frame_dct = 1;
chroma_format = CHROMA420;
matrix_coefficients = 5;
}
 
/* round to nearest multiple of coded macroblocks */
/* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
mb_width = (horizontal_size+15)/16;
mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
: (vertical_size+15)/16;
 
Coded_Picture_Width = 16*mb_width;
Coded_Picture_Height = 16*mb_height;
 
/* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
: Coded_Picture_Width>>1;
Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
: Coded_Picture_Height>>1;
/* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
block_count = Table_6_20[chroma_format-1];
 
for (cc=0; cc<3; cc++)
{
if (cc==0)
size = Coded_Picture_Width*Coded_Picture_Height;
else
size = Chroma_Width*Chroma_Height;
 
if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
Error("backward_reference_frame[] malloc failed\n");
 
if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
Error("forward_reference_frame[] malloc failed\n");
 
if (!(auxframe[cc] = (unsigned char *)malloc(size)))
Error("auxframe[] malloc failed\n");
 
if(Ersatz_Flag)
if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
Error("substitute_frame[] malloc failed\n");
 
 
if (base.scalable_mode==SC_SPAT)
{
/* this assumes lower layer is 4:2:0 */
if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
Error("llframe0 malloc failed\n");
if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
Error("llframe1 malloc failed\n");
}
}
 
/* SCALABILITY: Spatial */
if (base.scalable_mode==SC_SPAT)
{
if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
Error("lltmp malloc failed\n");
}
 
#ifdef DISPLAY
if (Output_Type==T_X11)
{
Initialize_Display_Process("");
Initialize_Dither_Matrix();
}
#endif /* DISPLAY */
 
}
 
void Error(text)
char *text;
{
cprintf(text);
}
 
/* Trace_Flag output */
void Print_Bits(code,bits,len)
int code,bits,len;
{
int i;
for (i=0; i<len; i++)
cprintf("%d",(code>>(bits-1-i))&1);
}
 
static int Headers()
{
int ret;
 
ld = &base;
 
/* return when end of sequence (0) or picture
header has been parsed (1) */
 
ret = Get_Hdr();
 
 
if (Two_Streams)
{
ld = &enhan;
if (Get_Hdr()!=ret && !Quiet_Flag)
cprintf("streams out of sync\n");
ld = &base;
}
 
return ret;
}
 
int Decode_Bitstream()
{
int ret;
int Bitstream_Framenum;
 
Bitstream_Framenum = 0;
 
for(;;)
{
 
#ifdef VERIFY
Clear_Verify_Headers();
#endif /* VERIFY */
 
ld->actual_file_ptr = ld->start_file_ptr;
 
ret = Headers();
if(ret==1)
{
ret = video_sequence(&Bitstream_Framenum);
}
else
return(ret);
}
 
}
 
 
static void Deinitialize_Sequence()
{
int i;
 
/* clear flags */
base.MPEG2_Flag=0;
 
for(i=0;i<3;i++)
{
free(backward_reference_frame[i]);
free(forward_reference_frame[i]);
free(auxframe[i]);
 
if (base.scalable_mode==SC_SPAT)
{
free(llframe0[i]);
free(llframe1[i]);
}
}
 
if (base.scalable_mode==SC_SPAT)
free(lltmp);
 
#ifdef DISPLAY
if (Output_Type==T_X11)
Terminate_Display_Process();
#endif
}
 
 
static int video_sequence(Bitstream_Framenumber)
int *Bitstream_Framenumber;
{
int Bitstream_Framenum;
int Sequence_Framenum;
int Return_Value;
 
char tmp[100];
 
Bitstream_Framenum = *Bitstream_Framenumber;
Sequence_Framenum=0;
 
Initialize_Sequence();
 
/* decode picture whose header has already been parsed in
Decode_Bitstream() */
 
ld->px = 310+(rand()%(500-Coded_Picture_Width));
ld->py = 100+(rand()%(400-Coded_Picture_Height));
sprintf(tmp,"Wx = %3d Wy = %3d",Coded_Picture_Width,Coded_Picture_Height);
grx_text(tmp,ld->px,ld->py-10,rgb16(255,255,255),0);
 
Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
 
/* update picture numbers */
if (!Second_Field)
{
Bitstream_Framenum++;
Sequence_Framenum++;
}
 
fsf_schedule_next_timed_job(NULL, NULL, NULL, NULL, NULL);
 
/* loop through the rest of the pictures in the sequence */
while ((Return_Value=Headers()))
{
Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
 
if (!Second_Field)
{
Bitstream_Framenum++;
Sequence_Framenum++;
}
 
fsf_schedule_next_timed_job(NULL, NULL, NULL, NULL, NULL);
}
 
/* put last frame */
if (Sequence_Framenum!=0)
{
Output_Last_Frame_of_Sequence(Bitstream_Framenum);
}
 
Deinitialize_Sequence();
 
#ifdef VERIFY
Clear_Verify_Headers();
#endif /* VERIFY */
 
*Bitstream_Framenumber = Bitstream_Framenum;
return(Return_Value);
}
 
 
 
static void Clear_Options()
{
Verbose_Flag = 0;
Output_Type = 0;
Output_Picture_Filename = " ";
hiQdither = 0;
Output_Type = 0;
Frame_Store_Flag = 0;
Spatial_Flag = 0;
Lower_Layer_Picture_Filename = " ";
Reference_IDCT_Flag = 0;
Trace_Flag = 0;
Quiet_Flag = 0;
Ersatz_Flag = 0;
Substitute_Picture_Filename = " ";
Two_Streams = 0;
Enhancement_Layer_Bitstream_Filename = " ";
Big_Picture_Flag = 0;
Main_Bitstream_Flag = 0;
Main_Bitstream_Filename = " ";
Verify_Flag = 0;
Stats_Flag = 0;
User_Data_Flag = 0;
}
 
 
#ifdef DEBUG
static void Print_Options()
{
printf("Verbose_Flag = %d\n", Verbose_Flag);
printf("Output_Type = %d\n", Output_Type);
printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
printf("hiQdither = %d\n", hiQdither);
printf("Output_Type = %d\n", Output_Type);
printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
printf("Spatial_Flag = %d\n", Spatial_Flag);
printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
printf("Trace_Flag = %d\n", Trace_Flag);
printf("Quiet_Flag = %d\n", Quiet_Flag);
printf("Ersatz_Flag = %d\n", Ersatz_Flag);
printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
printf("Two_Streams = %d\n", Two_Streams);
printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
printf("Verify_Flag = %d\n", Verify_Flag);
printf("Stats_Flag = %d\n", Stats_Flag);
printf("User_Data_Flag = %d\n", User_Data_Flag);
 
}
#endif
/advdemos/branches/advdemos/fsf/mpeg2/getvlc.h
0,0 → 1,491
/* getvlc.h, variable length code tables */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
/* NOTE: #define constants such as MACROBLOCK_QUANT are upper case
as per C programming convention. However, the MPEG document
(ISO/IEC 13818-2) lists them in all lower case (e.g. Annex B) */
 
/* NOTE: the VLC tables are in a flash format---a transformation
of the tables in Annex B to a form more convenient towards
parallel (more than one-bit-at-a-time) decoding */
 
typedef struct {
char val, len;
} VLCtab;
 
typedef struct {
char run, level, len;
} DCTtab;
 
/* Table B-3, macroblock_type in P-pictures, codes 001..1xx */
static VLCtab PMBtab0[8] = {
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,3},
{MACROBLOCK_PATTERN,2}, {MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,1}
};
 
/* Table B-3, macroblock_type in P-pictures, codes 000001..00011x */
static VLCtab PMBtab1[8] = {
{ERROR,0},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,6},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,5}, {MACROBLOCK_QUANT|MACROBLOCK_PATTERN,5},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,5}, {MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_INTRA,5}, {MACROBLOCK_INTRA,5}
};
 
/* Table B-4, macroblock_type in B-pictures, codes 0010..11xx */
static VLCtab BMBtab0[16] = {
{ERROR,0},
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,4},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-4, macroblock_type in B-pictures, codes 000001..00011x */
static VLCtab BMBtab1[8] = {
{ERROR,0},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,5},
{MACROBLOCK_INTRA,5},
{MACROBLOCK_INTRA,5}
};
 
/* Table B-5, macroblock_type in spat. scal. I-pictures, codes 0001..1xxx */
static VLCtab spIMBtab[16] = {
{ERROR,0},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,4},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,4},
{MACROBLOCK_INTRA,4},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}, {PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,1}
};
 
/* Table B-6, macroblock_type in spat. scal. P-pictures, codes 0010..11xx */
static VLCtab spPMBtab0[16] =
{
{ERROR,0},
{ERROR,0},
{MACROBLOCK_MOTION_FORWARD,4},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3}, {MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3}, {SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-6, macroblock_type in spat. scal. P-pictures, codes 0000010..000111x */
static VLCtab spPMBtab1[16] = {
{ERROR,0},
{ERROR,0},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,7},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,7},
{MACROBLOCK_PATTERN,7},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,7},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,7},
{MACROBLOCK_INTRA,7},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_PATTERN,6}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 0010..11xx */
static VLCtab spBMBtab0[14] = {
{MACROBLOCK_MOTION_FORWARD,4},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,4},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,3},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2},
{MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,2}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 0000100..000111x */
static VLCtab spBMBtab1[12] = {
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,7},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,7},
{MACROBLOCK_INTRA,7},
{MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,7},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,6}
};
 
/* Table B-7, macroblock_type in spat. scal. B-pictures, codes 00000100x..000001111 */
static VLCtab spBMBtab2[8] = {
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,8},
{MACROBLOCK_QUANT|MACROBLOCK_INTRA,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_FORWARD|MACROBLOCK_PATTERN,8},
{SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG|MACROBLOCK_QUANT|MACROBLOCK_MOTION_BACKWARD|MACROBLOCK_PATTERN,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_QUANT|MACROBLOCK_PATTERN,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS,9},
{PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS|MACROBLOCK_PATTERN,9}
};
 
/* Table B-8, macroblock_type in spat. scal. B-pictures, codes 001..1xx */
static VLCtab SNRMBtab[8] = {
{ERROR,0},
{0,3},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{MACROBLOCK_QUANT|MACROBLOCK_PATTERN,2},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1},
{MACROBLOCK_PATTERN,1}
};
 
/* Table B-10, motion_code, codes 0001 ... 01xx */
static VLCtab MVtab0[8] =
{ {ERROR,0}, {3,3}, {2,2}, {2,2}, {1,1}, {1,1}, {1,1}, {1,1}
};
 
/* Table B-10, motion_code, codes 0000011 ... 000011x */
static VLCtab MVtab1[8] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {7,6}, {6,6}, {5,6}, {4,5}, {4,5}
};
 
/* Table B-10, motion_code, codes 0000001100 ... 000001011x */
static VLCtab MVtab2[12] =
{ {16,9}, {15,9}, {14,9}, {13,9},
{12,9}, {11,9}, {10,8}, {10,8},
{9,8}, {9,8}, {8,8}, {8,8}
};
 
/* Table B-9, coded_block_pattern, codes 01000 ... 111xx */
static VLCtab CBPtab0[32] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{62,5}, {2,5}, {61,5}, {1,5}, {56,5}, {52,5}, {44,5}, {28,5},
{40,5}, {20,5}, {48,5}, {12,5}, {32,4}, {32,4}, {16,4}, {16,4},
{8,4}, {8,4}, {4,4}, {4,4}, {60,3}, {60,3}, {60,3}, {60,3}
};
 
/* Table B-9, coded_block_pattern, codes 00000100 ... 001111xx */
static VLCtab CBPtab1[64] =
{ {ERROR,0}, {ERROR,0}, {ERROR,0}, {ERROR,0},
{58,8}, {54,8}, {46,8}, {30,8},
{57,8}, {53,8}, {45,8}, {29,8}, {38,8}, {26,8}, {37,8}, {25,8},
{43,8}, {23,8}, {51,8}, {15,8}, {42,8}, {22,8}, {50,8}, {14,8},
{41,8}, {21,8}, {49,8}, {13,8}, {35,8}, {19,8}, {11,8}, {7,8},
{34,7}, {34,7}, {18,7}, {18,7}, {10,7}, {10,7}, {6,7}, {6,7},
{33,7}, {33,7}, {17,7}, {17,7}, {9,7}, {9,7}, {5,7}, {5,7},
{63,6}, {63,6}, {63,6}, {63,6}, {3,6}, {3,6}, {3,6}, {3,6},
{36,6}, {36,6}, {36,6}, {36,6}, {24,6}, {24,6}, {24,6}, {24,6}
};
 
/* Table B-9, coded_block_pattern, codes 000000001 ... 000000111 */
static VLCtab CBPtab2[8] =
{ {ERROR,0}, {0,9}, {39,9}, {27,9}, {59,9}, {55,9}, {47,9}, {31,9}
};
 
/* Table B-1, macroblock_address_increment, codes 00010 ... 011xx */
static VLCtab MBAtab1[16] =
{ {ERROR,0}, {ERROR,0}, {7,5}, {6,5}, {5,4}, {5,4}, {4,4}, {4,4},
{3,3}, {3,3}, {3,3}, {3,3}, {2,3}, {2,3}, {2,3}, {2,3}
};
 
/* Table B-1, macroblock_address_increment, codes 00000011000 ... 0000111xxxx */
static VLCtab MBAtab2[104] =
{
{33,11}, {32,11}, {31,11}, {30,11}, {29,11}, {28,11}, {27,11}, {26,11},
{25,11}, {24,11}, {23,11}, {22,11}, {21,10}, {21,10}, {20,10}, {20,10},
{19,10}, {19,10}, {18,10}, {18,10}, {17,10}, {17,10}, {16,10}, {16,10},
{15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8}, {15,8},
{14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8}, {14,8},
{13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8}, {13,8},
{12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8}, {12,8},
{11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8}, {11,8},
{10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8}, {10,8},
{9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7},
{9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7}, {9,7},
{8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7},
{8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}, {8,7}
};
 
/* Table B-12, dct_dc_size_luminance, codes 00xxx ... 11110 */
static VLCtab DClumtab0[32] =
{ {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2},
{2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2},
{0, 3}, {0, 3}, {0, 3}, {0, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3},
{4, 3}, {4, 3}, {4, 3}, {4, 3}, {5, 4}, {5, 4}, {6, 5}, {ERROR, 0}
};
 
/* Table B-12, dct_dc_size_luminance, codes 111110xxx ... 111111111 */
static VLCtab DClumtab1[16] =
{ {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6}, {7, 6},
{8, 7}, {8, 7}, {8, 7}, {8, 7}, {9, 8}, {9, 8}, {10,9}, {11,9}
};
 
/* Table B-13, dct_dc_size_chrominance, codes 00xxx ... 11110 */
static VLCtab DCchromtab0[32] =
{ {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2}, {0, 2},
{1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2},
{2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2},
{3, 3}, {3, 3}, {3, 3}, {3, 3}, {4, 4}, {4, 4}, {5, 5}, {ERROR, 0}
};
 
/* Table B-13, dct_dc_size_chrominance, codes 111110xxxx ... 1111111111 */
static VLCtab DCchromtab1[32] =
{ {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6},
{6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6}, {6, 6},
{7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7},
{8, 8}, {8, 8}, {8, 8}, {8, 8}, {9, 9}, {9, 9}, {10,10}, {11,10}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0100 ... 1xxx (used for first (DC) coefficient)
*/
DCTtab DCTtabfirst[12] =
{
{0,2,4}, {2,1,4}, {1,1,3}, {1,1,3},
{0,1,1}, {0,1,1}, {0,1,1}, {0,1,1},
{0,1,1}, {0,1,1}, {0,1,1}, {0,1,1}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0100 ... 1xxx (used for all other coefficients)
*/
DCTtab DCTtabnext[12] =
{
{0,2,4}, {2,1,4}, {1,1,3}, {1,1,3},
{64,0,2}, {64,0,2}, {64,0,2}, {64,0,2}, /* EOB */
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 000001xx ... 00111xxx
*/
DCTtab DCTtab0[60] =
{
{65,0,6}, {65,0,6}, {65,0,6}, {65,0,6}, /* Escape */
{2,2,7}, {2,2,7}, {9,1,7}, {9,1,7},
{0,4,7}, {0,4,7}, {8,1,7}, {8,1,7},
{7,1,6}, {7,1,6}, {7,1,6}, {7,1,6},
{6,1,6}, {6,1,6}, {6,1,6}, {6,1,6},
{1,2,6}, {1,2,6}, {1,2,6}, {1,2,6},
{5,1,6}, {5,1,6}, {5,1,6}, {5,1,6},
{13,1,8}, {0,6,8}, {12,1,8}, {11,1,8},
{3,2,8}, {1,3,8}, {0,5,8}, {10,1,8},
{0,3,5}, {0,3,5}, {0,3,5}, {0,3,5},
{0,3,5}, {0,3,5}, {0,3,5}, {0,3,5},
{4,1,5}, {4,1,5}, {4,1,5}, {4,1,5},
{4,1,5}, {4,1,5}, {4,1,5}, {4,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5}
};
 
/* Table B-15, DCT coefficients table one,
* codes 000001xx ... 11111111
*/
DCTtab DCTtab0a[252] =
{
{65,0,6}, {65,0,6}, {65,0,6}, {65,0,6}, /* Escape */
{7,1,7}, {7,1,7}, {8,1,7}, {8,1,7},
{6,1,7}, {6,1,7}, {2,2,7}, {2,2,7},
{0,7,6}, {0,7,6}, {0,7,6}, {0,7,6},
{0,6,6}, {0,6,6}, {0,6,6}, {0,6,6},
{4,1,6}, {4,1,6}, {4,1,6}, {4,1,6},
{5,1,6}, {5,1,6}, {5,1,6}, {5,1,6},
{1,5,8}, {11,1,8}, {0,11,8}, {0,10,8},
{13,1,8}, {12,1,8}, {3,2,8}, {1,4,8},
{2,1,5}, {2,1,5}, {2,1,5}, {2,1,5},
{2,1,5}, {2,1,5}, {2,1,5}, {2,1,5},
{1,2,5}, {1,2,5}, {1,2,5}, {1,2,5},
{1,2,5}, {1,2,5}, {1,2,5}, {1,2,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{3,1,5}, {3,1,5}, {3,1,5}, {3,1,5},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{1,1,3}, {1,1,3}, {1,1,3}, {1,1,3},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4}, /* EOB */
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{64,0,4}, {64,0,4}, {64,0,4}, {64,0,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,3,4}, {0,3,4}, {0,3,4}, {0,3,4},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,1,2}, {0,1,2}, {0,1,2}, {0,1,2},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,2,3}, {0,2,3}, {0,2,3}, {0,2,3},
{0,4,5}, {0,4,5}, {0,4,5}, {0,4,5},
{0,4,5}, {0,4,5}, {0,4,5}, {0,4,5},
{0,5,5}, {0,5,5}, {0,5,5}, {0,5,5},
{0,5,5}, {0,5,5}, {0,5,5}, {0,5,5},
{9,1,7}, {9,1,7}, {1,3,7}, {1,3,7},
{10,1,7}, {10,1,7}, {0,8,7}, {0,8,7},
{0,9,7}, {0,9,7}, {0,12,8}, {0,13,8},
{2,3,8}, {4,2,8}, {0,14,8}, {0,15,8}
};
 
/* Table B-14, DCT coefficients table zero,
* codes 0000001000 ... 0000001111
*/
DCTtab DCTtab1[8] =
{
{16,1,10}, {5,2,10}, {0,7,10}, {2,3,10},
{1,4,10}, {15,1,10}, {14,1,10}, {4,2,10}
};
 
/* Table B-15, DCT coefficients table one,
* codes 000000100x ... 000000111x
*/
DCTtab DCTtab1a[8] =
{
{5,2,9}, {5,2,9}, {14,1,9}, {14,1,9},
{2,4,10}, {16,1,10}, {15,1,9}, {15,1,9}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 000000010000 ... 000000011111
*/
DCTtab DCTtab2[16] =
{
{0,11,12}, {8,2,12}, {4,3,12}, {0,10,12},
{2,4,12}, {7,2,12}, {21,1,12}, {20,1,12},
{0,9,12}, {19,1,12}, {18,1,12}, {1,5,12},
{3,3,12}, {0,8,12}, {6,2,12}, {17,1,12}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 0000000010000 ... 0000000011111
*/
DCTtab DCTtab3[16] =
{
{10,2,13}, {9,2,13}, {5,3,13}, {3,4,13},
{2,5,13}, {1,7,13}, {1,6,13}, {0,15,13},
{0,14,13}, {0,13,13}, {0,12,13}, {26,1,13},
{25,1,13}, {24,1,13}, {23,1,13}, {22,1,13}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 00000000010000 ... 00000000011111
*/
DCTtab DCTtab4[16] =
{
{0,31,14}, {0,30,14}, {0,29,14}, {0,28,14},
{0,27,14}, {0,26,14}, {0,25,14}, {0,24,14},
{0,23,14}, {0,22,14}, {0,21,14}, {0,20,14},
{0,19,14}, {0,18,14}, {0,17,14}, {0,16,14}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 000000000010000 ... 000000000011111
*/
DCTtab DCTtab5[16] =
{
{0,40,15}, {0,39,15}, {0,38,15}, {0,37,15},
{0,36,15}, {0,35,15}, {0,34,15}, {0,33,15},
{0,32,15}, {1,14,15}, {1,13,15}, {1,12,15},
{1,11,15}, {1,10,15}, {1,9,15}, {1,8,15}
};
 
/* Table B-14/15, DCT coefficients table zero / one,
* codes 0000000000010000 ... 0000000000011111
*/
DCTtab DCTtab6[16] =
{
{1,18,16}, {1,17,16}, {1,16,16}, {1,15,16},
{6,3,16}, {16,2,16}, {15,2,16}, {14,2,16},
{13,2,16}, {12,2,16}, {11,2,16}, {31,1,16},
{30,1,16}, {29,1,16}, {28,1,16}, {27,1,16}
};
 
/advdemos/branches/advdemos/fsf/mpeg2/const.h
0,0 → 1,141
/*
* Project: S.Ha.R.K.
*
* Coordinators:
* Giorgio Buttazzo <giorgio@sssup.it>
* Paolo Gai <pj@gandalf.sssup.it>
*
* Authors :
* Paolo Gai <pj@gandalf.sssup.it>
* Massimiliano Giorgi <massy@gandalf.sssup.it>
* Luca Abeni <luca@gandalf.sssup.it>
* (see the web pages for full authors list)
*
* ReTiS Lab (Scuola Superiore S.Anna - Pisa - Italy)
*
* http://www.sssup.it
* http://retis.sssup.it
* http://shark.sssup.it
*/
 
 
/**
------------
CVS : $Id: const.h,v 1.1.1.1 2004-05-24 17:54:51 giacomo Exp $
 
File: $File$
Revision: $Revision: 1.1.1.1 $
Last update: $Date: 2004-05-24 17:54:51 $
------------
**/
 
/*
* Copyright (C) 2000 Marco Dallera and Marco Fiocca
*
* This program 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.
*
* This program 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
*
*/
 
/*
* AUTO
*
* Another Unuseful Track simulatOr
*
* Authors: Marco Dallera
* Marco Fiocca
*
*/
 
/* ------------------ */
/* Useful constants */
/* ------------------ */
 
#ifndef __CONST_H_
 
#define __CONST_H_
 
/* Screen dimensions */
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BIT_COLORS 8
 
/* Visible area */
#define TEL_WIDTH 50
#define TEL_HEIGHT 50
 
/* Car dimensions */
#define CAR_WIDTH 12
#define CAR_HEIGHT 12
#define CAR_W 8
#define CAR_H 10
 
/* Track dimensions */
#define TRACK_WIDTH 500
#define TRACK_HEIGHT 500
 
/* Track position */
#define TRACK_X1 0
#define TRACK_Y1 0
#define TRACK_X2 TRACK_X1+TRACK_WIDTH-1
#define TRACK_Y2 TRACK_Y1+TRACK_HEIGHT-1
 
/* Max number of car on track */
#define MAX_CAR_NUMBER 10
#define DRIVERS_NUMBER 20
#define MAX_DRIVER_NAME_LENGTH 20
#define MAX_TRACK_NAME_LENGTH 20
#define TRACK_NUMBER 4
 
/* Lap direction */
#define CLOCK 0
#define ANTICLOCK 1
 
/* Information display coords */
#define CMD_WIDTH TRACK_WIDTH
#define CMD_HEIGHT (SCREEN_HEIGHT-TRACK_HEIGHT-3)
 
/* Car position limits */
#define MIN_CAR_X (TRACK_X1 + CAR_WIDTH/2 + 4)
#define MIN_CAR_Y (TRACK_Y1 + CAR_HEIGHT/2 + 4)
#define MAX_CAR_X (TRACK_X2 - CAR_WIDTH/2 - 4)
#define MAX_CAR_Y (TRACK_Y2 - CAR_HEIGHT/2 - 4)
 
/* Road constants */
#define LEFT_ONLY 10
#define RIGHT_ONLY 11
#define ROAD_OK 12
#define NO_ROAD 13
 
/* Collision constants */
#define COLLISION_LEFT 20
#define COLLISION_RIGHT 21
#define COLLISION_BACK 22
#define NO_COLL 0
 
/* CAB constants */
#define ROAD_MSG_DIM sizeof(road_info)
#define ROAD_MSG_READER 4
 
#define CAR_MSG_DIM sizeof(car_status)
#define CAR_MSG_READER 5
 
/* Tasks parameters */
#define SENSOR_WCET 3000
#define SENSOR_PERIOD 40000
#define CONTROL_WCET 1000
#define CONTROL_PERIOD 40000
 
#endif
 
/advdemos/branches/advdemos/fsf/mpeg2/mpeg2dec.h
0,0 → 1,129
/* mpeg2dec.h, MPEG specific defines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#define ERROR (-1)
 
#define PICTURE_START_CODE 0x100
#define SLICE_START_CODE_MIN 0x101
#define SLICE_START_CODE_MAX 0x1AF
#define USER_DATA_START_CODE 0x1B2
#define SEQUENCE_HEADER_CODE 0x1B3
#define SEQUENCE_ERROR_CODE 0x1B4
#define EXTENSION_START_CODE 0x1B5
#define SEQUENCE_END_CODE 0x1B7
#define GROUP_START_CODE 0x1B8
#define SYSTEM_START_CODE_MIN 0x1B9
#define SYSTEM_START_CODE_MAX 0x1FF
 
#define ISO_END_CODE 0x1B9
#define PACK_START_CODE 0x1BA
#define SYSTEM_START_CODE 0x1BB
 
#define VIDEO_ELEMENTARY_STREAM 0x1e0
 
/* scalable_mode */
#define SC_NONE 0
#define SC_DP 1
#define SC_SPAT 2
#define SC_SNR 3
#define SC_TEMP 4
 
/* picture coding type */
#define I_TYPE 1
#define P_TYPE 2
#define B_TYPE 3
#define D_TYPE 4
 
/* picture structure */
#define TOP_FIELD 1
#define BOTTOM_FIELD 2
#define FRAME_PICTURE 3
 
/* macroblock type */
#define MACROBLOCK_INTRA 1
#define MACROBLOCK_PATTERN 2
#define MACROBLOCK_MOTION_BACKWARD 4
#define MACROBLOCK_MOTION_FORWARD 8
#define MACROBLOCK_QUANT 16
#define SPATIAL_TEMPORAL_WEIGHT_CODE_FLAG 32
#define PERMITTED_SPATIAL_TEMPORAL_WEIGHT_CLASS 64
 
 
/* motion_type */
#define MC_FIELD 1
#define MC_FRAME 2
#define MC_16X8 2
#define MC_DMV 3
 
/* mv_format */
#define MV_FIELD 0
#define MV_FRAME 1
 
/* chroma_format */
#define CHROMA420 1
#define CHROMA422 2
#define CHROMA444 3
 
/* extension start code IDs */
 
#define SEQUENCE_EXTENSION_ID 1
#define SEQUENCE_DISPLAY_EXTENSION_ID 2
#define QUANT_MATRIX_EXTENSION_ID 3
#define COPYRIGHT_EXTENSION_ID 4
#define SEQUENCE_SCALABLE_EXTENSION_ID 5
#define PICTURE_DISPLAY_EXTENSION_ID 7
#define PICTURE_CODING_EXTENSION_ID 8
#define PICTURE_SPATIAL_SCALABLE_EXTENSION_ID 9
#define PICTURE_TEMPORAL_SCALABLE_EXTENSION_ID 10
 
#define ZIG_ZAG 0
 
#define PROFILE_422 (128+5)
#define MAIN_LEVEL 8
 
/* Layers: used by Verbose_Flag, Verifier_Flag, Stats_Flag, and Trace_Flag */
#define NO_LAYER 0
#define SEQUENCE_LAYER 1
#define PICTURE_LAYER 2
#define SLICE_LAYER 3
#define MACROBLOCK_LAYER 4
#define BLOCK_LAYER 5
#define EVENT_LAYER 6
#define ALL_LAYERS 7
 
 
 
#define FILENAME_LENGTH 256
 
 
 
 
#define MB_WEIGHT 32
#define MB_CLASS4 64
 
/advdemos/branches/advdemos/fsf/mpeg2/store.c
0,0 → 1,319
/* store.c, picture output routines */
 
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
 
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
 
#include <stdlib.h>
 
#include "drivers/glib.h"
 
#include "config.h"
#include "global.h"
 
extern DWORD flbaddr;
 
static void conv422to444 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
static void conv420to422 _ANSI_ARGS_((unsigned char *src, unsigned char *dst));
 
__inline__ WORD down32to16(unsigned char r, unsigned char g, unsigned char b)
{
return ((b&0xf8)>>3)|((g&0xfc)<<3)|((r&0xf8)<<8);
}
 
void Write_Frame _ANSI_ARGS_((unsigned char *src[], int frame))
{
int i, j;
int y, u, v, r, g, b;
// int rm=0,gm=0,bm=0;
int crv, cbu, cgu, cgv;
unsigned char *py, *pu, *pv;
int height, width, incr;
static unsigned char *u422, *v422, *u444, *v444;
incr = width = Coded_Picture_Width ;
height = Coded_Picture_Height;
 
if (chroma_format==CHROMA444)
{
u444 = src[1];
v444 = src[2];
}
else
{
if (!u444)
{
if (chroma_format==CHROMA420)
{
if (!(u422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
if (!(v422 = (unsigned char *)malloc((Coded_Picture_Width>>1)
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (!(u444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
 
if (!(v444 = (unsigned char *)malloc(Coded_Picture_Width
*Coded_Picture_Height)))
Error("malloc failed");
}
 
if (chroma_format==CHROMA420)
{
conv420to422(src[1],u422);
conv420to422(src[2],v422);
conv422to444(u422,u444);
conv422to444(v422,v444);
}
else
{
conv422to444(src[1],u444);
conv422to444(src[2],v444);
}
}
 
/* matrix coefficients */
crv = Inverse_Table_6_9[matrix_coefficients][0];
cbu = Inverse_Table_6_9[matrix_coefficients][1];
cgu = Inverse_Table_6_9[matrix_coefficients][2];
cgv = Inverse_Table_6_9[matrix_coefficients][3];
for (i=0; i<height; i++)
{
py = src[0] + incr*i;
pu = u444 + incr*i;
pv = v444 + incr*i;
 
for (j=0; j<width; j++)
{
u = *pu++ - 128;
v = *pv++ - 128;
y = 76309 * (*py++ - 16); /* (255/219)*65536 */
 
r = Clip[(y + crv*v + 32768)>>16];
g = Clip[(y - cgu*u - cgv*v + 32768)>>16];
b = Clip[(y + cbu*u + 32786)>>16];
 
*(WORD *)(flbaddr+((i+ld->py)*800+(j+ld->px))*2) = down32to16(r,g,b);
}
}
}
 
/*
void Display_Image(Dithered_Image)
unsigned char *Dithered_Image;
{
/ * display dithered image */
//}
 
 
/* horizontal 1:2 interpolation filter */
static void conv422to444(src,dst)
unsigned char *src,*dst;
{
int i, i2, w, j, im3, im2, im1, ip1, ip2, ip3;
 
w = Coded_Picture_Width>>1;
 
if (base.MPEG2_Flag)
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
i2 = i<<1;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 21 0 -52 0 159 256 159 0 -52 0 21 */
/* even samples (0 0 256 0 0) */
dst[i2] = src[i];
 
/* odd samples (21 -52 159 159 -52 21) */
dst[i2+1] = Clip[(int)(21*(src[im2]+src[ip3])
-52*(src[im1]+src[ip2])
+159*(src[i]+src[ip1])+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
else
{
for (j=0; j<Coded_Picture_Height; j++)
{
for (i=0; i<w; i++)
{
 
i2 = i<<1;
im3 = (i<3) ? 0 : i-3;
im2 = (i<2) ? 0 : i-2;
im1 = (i<1) ? 0 : i-1;
ip1 = (i<w-1) ? i+1 : w-1;
ip2 = (i<w-2) ? i+2 : w-1;
ip3 = (i<w-3) ? i+3 : w-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
dst[i2] = Clip[(int)( 5*src[im3]
-21*src[im2]
+70*src[im1]
+228*src[i]
-37*src[ip1]
+11*src[ip2]+128)>>8];
 
dst[i2+1] = Clip[(int)( 5*src[ip3]
-21*src[ip2]
+70*src[ip1]
+228*src[i]
-37*src[im1]
+11*src[im2]+128)>>8];
}
src+= w;
dst+= Coded_Picture_Width;
}
}
}
 
/* vertical 1:2 interpolation filter */
static void conv420to422(src,dst)
unsigned char *src,*dst;
{
int w, h, i, j, j2;
int jm6, jm5, jm4, jm3, jm2, jm1, jp1, jp2, jp3, jp4, jp5, jp6, jp7;
 
w = Coded_Picture_Width>>1;
h = Coded_Picture_Height>>1;
 
if (progressive_frame)
{
/* intra frame */
for (i=0; i<w; i++)
{
for (j=0; j<h; j++)
{
j2 = j<<1;
jm3 = (j<3) ? 0 : j-3;
jm2 = (j<2) ? 0 : j-2;
jm1 = (j<1) ? 0 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp2 = (j<h-2) ? j+2 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
 
/* FIR filter coefficients (*256): 5 -21 70 228 -37 11 */
/* New FIR filter coefficients (*256): 3 -16 67 227 -32 7 */
dst[w*j2] = Clip[(int)( 3*src[w*jm3]
-16*src[w*jm2]
+67*src[w*jm1]
+227*src[w*j]
-32*src[w*jp1]
+7*src[w*jp2]+128)>>8];
 
dst[w*(j2+1)] = Clip[(int)( 3*src[w*jp3]
-16*src[w*jp2]
+67*src[w*jp1]
+227*src[w*j]
-32*src[w*jm1]
+7*src[w*jm2]+128)>>8];
}
src++;
dst++;
}
}
else
{
/* intra field */
for (i=0; i<w; i++)
{
for (j=0; j<h; j+=2)
{
j2 = j<<1;
 
/* top field */
jm6 = (j<6) ? 0 : j-6;
jm4 = (j<4) ? 0 : j-4;
jm2 = (j<2) ? 0 : j-2;
jp2 = (j<h-2) ? j+2 : h-2;
jp4 = (j<h-4) ? j+4 : h-2;
jp6 = (j<h-6) ? j+6 : h-2;
 
/* Polyphase FIR filter coefficients (*256): 2 -10 35 242 -18 5 */
/* New polyphase FIR filter coefficients (*256): 1 -7 30 248 -21 5 */
dst[w*j2] = Clip[(int)( 1*src[w*jm6]
-7*src[w*jm4]
+30*src[w*jm2]
+248*src[w*j]
-21*src[w*jp2]
+5*src[w*jp4]+128)>>8];
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+2)] = Clip[(int)( 7*src[w*jm4]
-35*src[w*jm2]
+194*src[w*j]
+110*src[w*jp2]
-24*src[w*jp4]
+4*src[w*jp6]+128)>>8];
 
/* bottom field */
jm5 = (j<5) ? 1 : j-5;
jm3 = (j<3) ? 1 : j-3;
jm1 = (j<1) ? 1 : j-1;
jp1 = (j<h-1) ? j+1 : h-1;
jp3 = (j<h-3) ? j+3 : h-1;
jp5 = (j<h-5) ? j+5 : h-1;
jp7 = (j<h-7) ? j+7 : h-1;
 
/* Polyphase FIR filter coefficients (*256): 11 -38 192 113 -30 8 */
/* New polyphase FIR filter coefficients (*256):7 -35 194 110 -24 4 */
dst[w*(j2+1)] = Clip[(int)( 7*src[w*jp5]
-35*src[w*jp3]
+194*src[w*jp1]
+110*src[w*jm1]
-24*src[w*jm3]
+4*src[w*jm5]+128)>>8];
 
dst[w*(j2+3)] = Clip[(int)( 1*src[w*jp7]
-7*src[w*jp5]
+30*src[w*jp3]
+248*src[w*jp1]
-21*src[w*jm1]
+5*src[w*jm3]+128)>>8];
}
src++;
dst++;
}
}
}
 
/advdemos/branches/advdemos/fsf/makefile
0,0 → 1,23
#
#
 
BASE=../..
include $(BASE)/config/config.mk
 
PROGS= test1 test2 test3
 
MPEG2 = ./mpeg2/getbits.o ./mpeg2/getblk.o ./mpeg2/gethdr.o ./mpeg2/getpic.o\
./mpeg2/getvlc.o ./mpeg2/idct.o ./mpeg2/idctref.o ./mpeg2/motion.o\
./mpeg2/mpeg2dec.o ./mpeg2/recon.o ./mpeg2/spatscal.o ./mpeg2/store.o\
./mpeg2/subspic.o ./mpeg2/systems.o ./mpeg2/verify.o ./mpeg2/gvideo.o
 
include $(BASE)/config/example.mk
 
test1:
make -f $(SUBMAKE) APP=test1 INIT= OTHEROBJS= OTHERINCL= SHARKOPT="__OLDCHAR__ __FIRST__"
 
test2:
make -f $(SUBMAKE) APP=test2 INIT= OTHEROBJS="initfile.o $(MPEG2)" OTHERINCL= SHARKOPT="__OLDCHAR__ __GRX__ __FIRST__"
test3:
make -f $(SUBMAKE) APP=test3 INIT= OTHEROBJS= OTHERINCL= SHARKOPT="__OLDCHAR__ __FIRST__"