summaryrefslogtreecommitdiff
path: root/apps/plugins/mpegplayer/audio_thread.c
blob: a901b721d88803cca6fd4c45094f18b23668cffb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * mpegplayer audio thread implementation
 *
 * Copyright (c) 2007 Michael Sevakis
 *
 * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "plugin.h"
#include "mpegplayer.h"
#include "codecs/libmad/bit.h"
#include "codecs/libmad/mad.h"

/** Audio stream and thread **/
struct pts_queue_slot;
struct audio_thread_data
{
    struct queue_event ev;  /* Our event queue to receive commands */
    int state;              /* Thread state */
    int status;             /* Media status (STREAM_PLAYING, etc.) */
    int mad_errors;         /* A count of the errors in each frame */
    unsigned samplerate;    /* Current stream sample rate */
    int nchannels;          /* Number of audio channels */
    struct dsp_config *dsp; /* The DSP we're using */
};

/* The audio thread is stolen from the core codec thread */
static struct event_queue audio_str_queue SHAREDBSS_ATTR;
static struct queue_sender_list audio_str_queue_send SHAREDBSS_ATTR;
struct stream audio_str IBSS_ATTR;

/* libmad related definitions */
static struct mad_stream stream IBSS_ATTR;
static struct mad_frame  frame IBSS_ATTR;
static struct mad_synth  synth IBSS_ATTR;

/*sbsample buffer for mad_frame*/
mad_fixed_t sbsample[2][36][32];

/* 2567 bytes */
static unsigned char mad_main_data[MAD_BUFFER_MDLEN];

/* There isn't enough room for this in IRAM on PortalPlayer, but there
   is for Coldfire. */

/* 4608 bytes */
#ifdef CPU_COLDFIRE
static mad_fixed_t mad_frame_overlap[2][32][18] IBSS_ATTR;
#else
static mad_fixed_t mad_frame_overlap[2][32][18];
#endif

/** A queue for saving needed information about MPEG audio packets **/
#define AUDIODESC_QUEUE_LEN  (1 << 5) /* 32 should be way more than sufficient -
                                         if not, the case is handled */
#define AUDIODESC_QUEUE_MASK (AUDIODESC_QUEUE_LEN-1)
struct audio_frame_desc
{
    uint32_t time;  /* Time stamp for packet in audio ticks       */
    ssize_t  size;  /* Number of unprocessed bytes left in packet */
};

 /* This starts out wr == rd but will never be emptied to zero during
    streaming again in order to support initializing the first packet's
    timestamp without a special case */
struct
{
    /* Compressed audio data */
    uint8_t *start;  /* Start of encoded audio buffer */
    uint8_t *ptr;    /* Pointer to next encoded audio data */
    ssize_t used;    /* Number of bytes in MPEG audio buffer */
    /* Compressed audio data descriptors */
    unsigned read, write;
    struct audio_frame_desc *curr; /* Current slot */
    struct audio_frame_desc descs[AUDIODESC_QUEUE_LEN];
} audio_queue;

static inline int audiodesc_queue_count(void)
{
    return audio_queue.write - audio_queue.read;
}

static inline bool audiodesc_queue_full(void)
{
    return audio_queue.used >= MPA_MAX_FRAME_SIZE + MAD_BUFFER_GUARD ||
            audiodesc_queue_count() >= AUDIODESC_QUEUE_LEN;
}

/* Increments the queue tail postion - should be used to preincrement */
static inline void audiodesc_queue_add_tail(void)
{
    if (audiodesc_queue_full())
    {
        DEBUGF("audiodesc_queue_add_tail: audiodesc queue full!\n");
        return;
    }

    audio_queue.write++;
}

/* Increments the queue tail position - leaves one slot as current */
static inline bool audiodesc_queue_remove_head(void)
{
    if (audio_queue.write == audio_queue.read)
        return false;

    audio_queue.read++;
    return true;
}

/* Returns the "tail" at the index just behind the write index */
static inline struct audio_frame_desc * audiodesc_queue_tail(void)
{
    return &audio_queue.descs[(audio_queue.write - 1) & AUDIODESC_QUEUE_MASK];
}

/* Returns a pointer to the current head */
static inline struct audio_frame_desc * audiodesc_queue_head(void)
{
    return &audio_queue.descs[audio_queue.read & AUDIODESC_QUEUE_MASK];
}

/* Resets the pts queue - call when starting and seeking */
static void audio_queue_reset(void)
{
    audio_queue.ptr = audio_queue.start;
    audio_queue.used = 0;
    audio_queue.read = 0;
    audio_queue.write = 0;
    rb->memset(audio_queue.descs, 0, sizeof (audio_queue.descs));
    audio_queue.curr = audiodesc_queue_head();
}

static void audio_queue_advance_pos(ssize_t len)
{
    audio_queue.ptr        += len;
    audio_queue.used       -= len;
    audio_queue.curr->size -= len;
}

static int audio_buffer(struct stream *str, enum stream_parse_mode type)
{
    int ret = STREAM_OK;

    /* Carry any overshoot to the next size since we're technically
       -size bytes into it already. If size is negative an audio
       frame was split across packets. Old has to be saved before
       moving the head. */
    if (audio_queue.curr->size <= 0 && audiodesc_queue_remove_head())
    {
        struct audio_frame_desc *old = audio_queue.curr;
        audio_queue.curr = audiodesc_queue_head();
        audio_queue.curr->size += old->size;
        old->size = 0;
    }

    /* Add packets to compressed audio buffer until it's full or the
     * timestamp queue is full - whichever happens first */
    while (!audiodesc_queue_full())
    {
        ret = parser_get_next_data(str, type);
        struct audio_frame_desc *curr;
        ssize_t len;

        if (ret != STREAM_OK)
            break;

        /* Get data from next audio packet */
        len = str->curr_packet_end - str->curr_packet;

        if (str->pkt_flags & PKT_HAS_TS)
        {
            audiodesc_queue_add_tail();
            curr = audiodesc_queue_tail();
            curr->time = TS_TO_TICKS(str->pts);
            /* pts->size should have been zeroed when slot was
               freed */
        }
        else
        {
            /* Add to the one just behind the tail - this may be
             * the head or the previouly added tail - whether or
             * not we'll ever reach this is quite in question
             * since audio always seems to have every packet
             * timestamped */
            curr = audiodesc_queue_tail();
        }

        curr->size += len;

        /* Slide any remainder over to beginning */
        if (audio_queue.ptr > audio_queue.start && audio_queue.used > 0)
        {
            rb->memmove(audio_queue.start, audio_queue.ptr,
                        audio_queue.used);
        }

        /* Splice this packet onto any remainder */
        rb->memcpy(audio_queue.start + audio_queue.used,
                   str->curr_packet, len);

        audio_queue.used += len;
        audio_queue.ptr = audio_queue.start;

        rb->yield();
    }

    return ret;
}

/* Initialise libmad */
static void init_mad(void)
{
    /*init the sbsample buffer*/
    frame.sbsample = &sbsample;
    frame.sbsample_prev = &sbsample;
    
    mad_stream_init(&stream);
    mad_frame_init(&frame);
    mad_synth_init(&synth);

    /* We do this so libmad doesn't try to call codec_calloc() */
    rb->memset(mad_frame_overlap, 0, sizeof(mad_frame_overlap));
    frame.overlap = (void *)mad_frame_overlap;

    rb->memset(mad_main_data, 0, sizeof(mad_main_data));
    stream.main_data = &mad_main_data;
}

/* Sync audio stream to a particular frame - see main decoder loop for
 * detailed remarks */
static int audio_sync(struct audio_thread_data *td,
                      struct str_sync_data *sd)
{
    int retval = STREAM_MATCH;
    uint32_t sdtime = TS_TO_TICKS(clip_time(&audio_str, sd->time));
    uint32_t time;
    uint32_t duration = 0;
    struct stream *str;
    struct stream tmp_str;
    struct mad_header header;
    struct mad_stream stream;

    if (td->ev.id == STREAM_SYNC)
    {
        /* Actually syncing for playback - use real stream */
        time = 0;
        str = &audio_str;
    }
    else
    {
        /* Probing - use temp stream */
        time = INVALID_TIMESTAMP;
        str = &tmp_str;
        str->id = audio_str.id;
    }        

    str->hdr.pos = sd->sk.pos;
    str->hdr.limit = sd->sk.pos + sd->sk.len;

    mad_stream_init(&stream);
    mad_header_init(&header);

    while (1)
    {
        if (audio_buffer(str, STREAM_PM_RANDOM_ACCESS) == STREAM_DATA_END)
        {
            DEBUGF("audio_sync:STR_DATA_END\n  aqu:%ld swl:%ld swr:%ld\n",
                    audio_queue.used, str->hdr.win_left, str->hdr.win_right);
            if (audio_queue.used <= MAD_BUFFER_GUARD)
                goto sync_data_end;
        }

        stream.error = 0;
        mad_stream_buffer(&stream, audio_queue.ptr, audio_queue.used);

        if (stream.sync && mad_stream_sync(&stream) < 0)
        {
            DEBUGF(" audio: mad_stream_sync failed\n");
            audio_queue_advance_pos(MAX(audio_queue.curr->size - 1, 1));
            continue;
        }

        stream.sync = 0;

        if (mad_header_decode(&header, &stream) < 0)
        {
            DEBUGF(" audio: mad_header_decode failed:%s\n",
                   mad_stream_errorstr(&stream));
            audio_queue_advance_pos(1);
            continue;
        }

        duration = 32*MAD_NSBSAMPLES(&header);
        time = audio_queue.curr->time;

        DEBUGF(" audio: ft:%u t:%u fe:%u nsamp:%u sampr:%u\n",
               (unsigned)TICKS_TO_TS(time), (unsigned)sd->time,
               (unsigned)TICKS_TO_TS(time + duration),
               (unsigned)duration, header.samplerate);

        audio_queue_advance_pos(stream.this_frame - audio_queue.ptr);

        if (time <= sdtime && sdtime < time + duration)
        {
            DEBUGF(" audio: ft<=t<fe\n");
            retval = STREAM_PERFECT_MATCH;
            break;
        }
        else if (time > sdtime)
        {
            DEBUGF(" audio: ft>t\n");
            break;
        }

        audio_queue_advance_pos(stream.next_frame - audio_queue.ptr);
        audio_queue.curr->time += duration;

        rb->yield();
    }

sync_data_end:
    if (td->ev.id == STREAM_FIND_END_TIME)
    {
        if (time != INVALID_TIMESTAMP)
        {
            time = TICKS_TO_TS(time);
            duration = TICKS_TO_TS(duration);
            sd->time = time + duration;
            retval = STREAM_PERFECT_MATCH;
        }
        else
        {
            retval = STREAM_NOT_FOUND;
        }
    }

    DEBUGF(" audio header: 0x%02X%02X%02X%02X\n",
           (unsigned)audio_queue.ptr[0], (unsigned)audio_queue.ptr[1],
           (unsigned)audio_queue.ptr[2], (unsigned)audio_queue.ptr[3]);

    return retval;
    (void)td;
}

static void audio_thread_msg(struct audio_thread_data *td)
{
    while (1)
    {
        intptr_t reply = 0;

        switch (td->ev.id)
        {
        case STREAM_PLAY:
            td->status = STREAM_PLAYING;

            switch (td->state)
            {
            case TSTATE_INIT:
                td->state = TSTATE_DECODE;
            case TSTATE_DECODE:
            case TSTATE_RENDER_WAIT:
            case TSTATE_RENDER_WAIT_END:
                break;

            case TSTATE_EOS:
                /* At end of stream - no playback possible so fire the
                 * completion event */
                stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0);
                break;
            }

            break;

        case STREAM_PAUSE:
            td->status = STREAM_PAUSED;
            reply = td->state != TSTATE_EOS;
            break;

        case STREAM_STOP:
            if (td->state == TSTATE_DATA)
                stream_clear_notify(&audio_str, DISK_BUF_DATA_NOTIFY);

            td->status = STREAM_STOPPED;
            td->state = TSTATE_EOS;

            reply = true;
            break;            

        case STREAM_RESET:
            if (td->state == TSTATE_DATA)
                stream_clear_notify(&audio_str, DISK_BUF_DATA_NOTIFY);

            td->status = STREAM_STOPPED;
            td->state = TSTATE_INIT;
            td->samplerate = 0;
            td->nchannels = 0;

            init_mad();
            td->mad_errors = 0;

            audio_queue_reset();

            reply = true;
            break;

        case STREAM_NEEDS_SYNC:
            reply = true; /* Audio always needs to */
            break;

        case STREAM_SYNC:
        case STREAM_FIND_END_TIME:
            if (td->state != TSTATE_INIT)
                break;

            reply = audio_sync(td, (struct str_sync_data *)td->ev.data);
            break;

        case DISK_BUF_DATA_NOTIFY:
            /* Our bun is done */
            if (td->state != TSTATE_DATA)
                break;

            td->state = TSTATE_DECODE;
            str_data_notify_received(&audio_str);
            break;

        case STREAM_QUIT:
            /* Time to go - make thread exit */
            td->state = TSTATE_EOS;
            return;
        }

        str_reply_msg(&audio_str, reply);

        if (td->status == STREAM_PLAYING)
        {
            switch (td->state)
            {
            case TSTATE_DECODE:
            case TSTATE_RENDER_WAIT:
            case TSTATE_RENDER_WAIT_END:
                /* These return when in playing state */
                return;
            }
        }

        str_get_msg(&audio_str, &td->ev);
    }
}

static void audio_thread(void)
{
    struct audio_thread_data td;
#ifdef HAVE_PRIORITY_SCHEDULING
    /* Up the priority since the core DSP over-yields internally */
    int old_priority = rb->thread_set_priority(THREAD_ID_CURRENT,
                                               PRIORITY_PLAYBACK-4);
#endif

    rb->memset(&td, 0, sizeof (td));
    td.status = STREAM_STOPPED;
    td.state = TSTATE_EOS;

    /* We need this here to init the EMAC for Coldfire targets */
    init_mad();

    td.dsp = (struct dsp_config *)rb->dsp_configure(NULL, DSP_MYDSP,
                                                    CODEC_IDX_AUDIO);
    rb->sound_set_pitch(PITCH_SPEED_100);
    rb->dsp_configure(td.dsp, DSP_RESET, 0);
    rb->dsp_configure(td.dsp, DSP_SET_SAMPLE_DEPTH, MAD_F_FRACBITS);

    goto message_wait;

    /* This is the decoding loop. */
    while (1)
    {
        td.state = TSTATE_DECODE;

        /* Check for any pending messages and process them */
        if (str_have_msg(&audio_str))
        {
        message_wait:
            /* Wait for a message to be queued */
            str_get_msg(&audio_str, &td.ev);

        message_process:
            /* Process a message already dequeued */
            audio_thread_msg(&td);

            switch (td.state)
            {
            /* These states are the only ones that should return */
            case TSTATE_DECODE:          goto audio_decode;
            case TSTATE_RENDER_WAIT:     goto render_wait;
            case TSTATE_RENDER_WAIT_END: goto render_wait_end;
            /* Anything else is interpreted as an exit */
            default:
            {
#ifdef HAVE_PRIORITY_SCHEDULING
                rb->thread_set_priority(THREAD_ID_CURRENT, old_priority);
#endif
                return;
                }
            }
        }

    audio_decode:

        /** Buffering **/
        switch (audio_buffer(&audio_str, STREAM_PM_STREAMING))
        {
        case STREAM_DATA_NOT_READY:
        {
            td.state = TSTATE_DATA;
            goto message_wait;
            } /* STREAM_DATA_NOT_READY: */

        case STREAM_DATA_END:
        {
            if (audio_queue.used > MAD_BUFFER_GUARD)
                break;

            /* Used up remainder of compressed audio buffer.
             * Force any residue to play if audio ended before
             * reaching the threshold */
            td.state = TSTATE_RENDER_WAIT_END;
            audio_queue_reset();

        render_wait_end:
            pcm_output_drain();

            while (pcm_output_used() > (ssize_t)PCMOUT_LOW_WM)
            {
                str_get_msg_w_tmo(&audio_str, &td.ev, 1);
                if (td.ev.id != SYS_TIMEOUT)
                    goto message_process;
            }

            td.state = TSTATE_EOS;
            if (td.status == STREAM_PLAYING)
                stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0);

            rb->yield();
            goto message_wait;
            } /* STREAM_DATA_END: */
        }

        /** Decoding **/
        mad_stream_buffer(&stream, audio_queue.ptr, audio_queue.used);

        int mad_stat = mad_frame_decode(&frame, &stream);

        ssize_t len = stream.next_frame - audio_queue.ptr;

        if (mad_stat != 0)
        {
            DEBUGF("audio: Stream error: %s\n",
                   mad_stream_errorstr(&stream));

            /* If something's goofed - try to perform resync by moving
             * at least one byte at a time */
            audio_queue_advance_pos(MAX(len, 1));

            if (stream.error == MAD_FLAG_INCOMPLETE
                || stream.error == MAD_ERROR_BUFLEN)
            {
                /* This makes the codec support partially corrupted files */
                if (++td.mad_errors <= MPA_MAX_FRAME_SIZE)
                {
                    stream.error = 0;
                    rb->yield();
                    continue;
                }
                DEBUGF("audio: Too many errors\n");
            }
            else if (MAD_RECOVERABLE(stream.error))
            {
                /* libmad says it can recover - just keep on decoding */
                rb->yield();
                continue;
            }
            else
            {
                /* Some other unrecoverable error */
                DEBUGF("audio: Unrecoverable error\n");
            }

            /* This is too hard - bail out */
            td.state = TSTATE_EOS;

            if (td.status == STREAM_PLAYING)
                stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0);

            td.status = STREAM_ERROR;
            goto message_wait;
        }

        /* Adjust sizes by the frame size */
        audio_queue_advance_pos(len);
        td.mad_errors = 0; /* Clear errors */

        /* Generate the pcm samples */
        mad_synth_frame(&synth, &frame);

        /** Output **/
        if (frame.header.samplerate != td.samplerate)
        {
            td.samplerate = frame.header.samplerate;
            rb->dsp_configure(td.dsp, DSP_SWITCH_FREQUENCY,
                              td.samplerate);
        }

        if (MAD_NCHANNELS(&frame.header) != td.nchannels)
        {
            td.nchannels = MAD_NCHANNELS(&frame.header);
            rb->dsp_configure(td.dsp, DSP_SET_STEREO_MODE,
                              td.nchannels == 1 ?
                                STEREO_MONO : STEREO_NONINTERLEAVED);
        }

        td.state  = TSTATE_RENDER_WAIT;

        /* Add a frame of audio to the pcm buffer. Maximum is 1152 samples. */
    render_wait:
        if (synth.pcm.length > 0)
        {
            struct pcm_frame_header *dst_hdr = pcm_output_get_buffer();
            const char *src[2] =
                { (char *)synth.pcm.samples[0], (char *)synth.pcm.samples[1] };
            int out_count = (synth.pcm.length * CLOCK_RATE
                                + (td.samplerate - 1)) / td.samplerate;
            ssize_t size = sizeof(*dst_hdr) + out_count*4;

            /* Wait for required amount of free buffer space */
            while (pcm_output_free() < size)
            {
                /* Wait one frame */
                int timeout = out_count*HZ / td.samplerate;
                str_get_msg_w_tmo(&audio_str, &td.ev, MAX(timeout, 1));
                if (td.ev.id != SYS_TIMEOUT)
                    goto message_process;
            }

            out_count = rb->dsp_process(td.dsp, dst_hdr->data, src,
                                        synth.pcm.length);

            if (out_count <= 0)
                break;

            dst_hdr->size = sizeof(*dst_hdr) + out_count*4;
            dst_hdr->time = audio_queue.curr->time;

            /* As long as we're on this timestamp, the time is just
               incremented by the number of samples */
            audio_queue.curr->time += out_count;

            /* Make this data available to DMA */
            pcm_output_add_data();
        }

        rb->yield();
    } /* end decoding loop */
}

/* Initializes the audio thread resources and starts the thread */
bool audio_thread_init(void)
{
    /* Initialise the encoded audio buffer and its descriptors */
    audio_queue.start = mpeg_malloc(AUDIOBUF_ALLOC_SIZE,
                                    MPEG_ALLOC_AUDIOBUF);
    if (audio_queue.start == NULL)
        return false;

    /* Start the audio thread */
    audio_str.hdr.q = &audio_str_queue;
    rb->queue_init(audio_str.hdr.q, false);

    /* We steal the codec thread for audio */
    rb->codec_thread_do_callback(audio_thread, &audio_str.thread);

    rb->queue_enable_queue_send(audio_str.hdr.q, &audio_str_queue_send,
                                audio_str.thread);

    /* Wait for thread to initialize */
    str_send_msg(&audio_str, STREAM_NULL, 0);

    return true;
}

/* Stops the audio thread */
void audio_thread_exit(void)
{
    if (audio_str.thread != 0)
    {
        str_post_msg(&audio_str, STREAM_QUIT, 0);
        rb->codec_thread_do_callback(NULL, NULL);
        audio_str.thread = 0;
    }
}
R_SetPatchNum(&hu_font[i], "STCFN091"); } else if (j==']') { R_SetPatchNum(hu_font2 +i, "DIG93"); R_SetPatchNum(&hu_font[i], "STCFN093"); } else if (j<97) { snprintf(buffer, sizeof(buffer), "STCFN%s%d", (j/10>0?"0":"00"), j); //NOTE ROCKHACK: "STCFN%.3d" R_SetPatchNum(hu_font2 +i, buffer); R_SetPatchNum(&hu_font[i], buffer); //jff 2/23/98 make all font chars defined, useful or not } else if (j>122) { snprintf(buffer, sizeof(buffer), "STBR%d", j); //NOTE: "STBR%.3d" R_SetPatchNum(hu_font2 +i, buffer); R_SetPatchNum(&hu_font[i], buffer); } else hu_font[i] = hu_font[0]; //jff 2/16/98 account for gap } // CPhipps - load patches for message background for (i=0; i<9; i++) { snprintf(buffer, sizeof(buffer), "BOX%c%c", "UCL"[i/3], "LCR"[i%3]); R_SetPatchNum(&hu_msgbg[i], buffer); } // CPhipps - load patches for keys and double keys for (i=0; i<6; i++) { snprintf(buffer, sizeof(buffer), "STKEYS%d", i); R_SetPatchNum(hu_fontk+i, buffer); } } // // HU_Stop() // // Make the heads-up displays inactive // // Passed nothing, returns nothing // void HU_Stop(void) { headsupactive = false; } // // HU_Start(void) // // Create and initialize the heads-up widgets, software machines to // maintain, update, and display information over the primary display // // This routine must be called after any change to the heads up configuration // in order for the changes to take effect in the actual displays // // Passed nothing, returns nothing // void HU_Start(void) { int i; const char* s; /* cph - const */ if (headsupactive) // stop before starting HU_Stop(); plr = &players[displayplayer]; // killough 3/7/98 message_on = false; message_dontfuckwithme = false; message_nottobefuckedwith = false; chat_on = false; // create the message widget // messages to player in upper-left of screen HUlib_initSText ( &w_message, HU_MSGX, HU_MSGY, HU_MSGHEIGHT, hu_font, HU_FONTSTART, hudcolor_mesg, &message_on ); //jff 2/16/98 added some HUD widgets // create the map title widget - map title display in lower left of automap HUlib_initTextLine ( &w_title, HU_TITLEX, HU_TITLEY, hu_font, HU_FONTSTART, hudcolor_titl ); // create the hud health widget // bargraph and number for amount of health, // lower left or upper right of screen HUlib_initTextLine ( &w_health, hud_distributed? HU_HEALTHX_D : HU_HEALTHX, //3/4/98 distribute hud_distributed? HU_HEALTHY_D : HU_HEALTHY, hu_font2, HU_FONTSTART, CR_GREEN ); // create the hud armor widget // bargraph and number for amount of armor, // lower left or upper right of screen HUlib_initTextLine ( &w_armor, hud_distributed? HU_ARMORX_D : HU_ARMORX, //3/4/98 distribute hud_distributed? HU_ARMORY_D : HU_ARMORY, hu_font2, HU_FONTSTART, CR_GREEN ); // create the hud ammo widget // bargraph and number for amount of ammo for current weapon, // lower left or lower right of screen HUlib_initTextLine ( &w_ammo, hud_distributed? HU_AMMOX_D : HU_AMMOX, //3/4/98 distribute hud_distributed? HU_AMMOY_D : HU_AMMOY, hu_font2, HU_FONTSTART, CR_GOLD ); // create the hud weapons widget // list of numbers of weapons possessed // lower left or lower right of screen HUlib_initTextLine ( &w_weapon, hud_distributed? HU_WEAPX_D : HU_WEAPX, //3/4/98 distribute hud_distributed? HU_WEAPY_D : HU_WEAPY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud keys widget // display of key letters possessed // lower left of screen HUlib_initTextLine ( &w_keys, hud_distributed? HU_KEYSX_D : HU_KEYSX, //3/4/98 distribute hud_distributed? HU_KEYSY_D : HU_KEYSY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud graphic keys widget // display of key graphics possessed // lower left of screen HUlib_initTextLine ( &w_gkeys, hud_distributed? HU_KEYSGX_D : HU_KEYSGX, //3/4/98 distribute hud_distributed? HU_KEYSY_D : HU_KEYSY, hu_fontk, HU_FONTSTART, CR_RED ); // create the hud monster/secret widget // totals and current values for kills, items, secrets // lower left of screen HUlib_initTextLine ( &w_monsec, hud_distributed? HU_MONSECX_D : HU_MONSECX, //3/4/98 distribute hud_distributed? HU_MONSECY_D : HU_MONSECY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud text refresh widget // scrolling display of last hud_msg_lines messages received if (hud_msg_lines>HU_MAXMESSAGES) hud_msg_lines=HU_MAXMESSAGES; //jff 4/21/98 if setup has disabled message list while active, turn it off message_list = hud_msg_lines > 1; //jff 8/8/98 initialize both ways //jff 2/26/98 add the text refresh widget initialization HUlib_initMText ( &w_rtext, 0, 0, 320, // SCREENWIDTH, (hud_msg_lines+2)*HU_REFRESHSPACING, hu_font, HU_FONTSTART, hudcolor_list, hu_msgbg, &message_list ); // initialize the automap's level title widget if (gamestate == GS_LEVEL) /* cph - stop SEGV here when not in level */ switch (gamemode) { case shareware: case registered: case retail: s = HU_TITLE; break; case commercial: default: // Ty 08/27/98 - modified to check mission for TNT/Plutonia s = (gamemission==pack_tnt) ? HU_TITLET : (gamemission==pack_plut) ? HU_TITLEP : HU_TITLE2; break; } else s = ""; while (*s) HUlib_addCharToTextLine(&w_title, *(s++)); // create the automaps coordinate widget // jff 3/3/98 split coord widget into three lines: x,y,z // jff 2/16/98 added HUlib_initTextLine ( &w_coordx, HU_COORDX, HU_COORDX_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); HUlib_initTextLine ( &w_coordy, HU_COORDX, HU_COORDY_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); HUlib_initTextLine ( &w_coordz, HU_COORDX, HU_COORDZ_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); // initialize the automaps coordinate widget //jff 3/3/98 split coordstr widget into 3 parts snprintf(hud_coordstrx,32*sizeof(char),"X: %d",0); //jff 2/22/98 added z s = hud_coordstrx; while (*s) HUlib_addCharToTextLine(&w_coordx, *(s++)); snprintf(hud_coordstry,32*sizeof(char),"Y: %d",0); //jff 3/3/98 split x,y,z s = hud_coordstry; while (*s) HUlib_addCharToTextLine(&w_coordy, *(s++)); snprintf(hud_coordstrz,32*sizeof(char),"Z: %d",0); //jff 3/3/98 split x,y,z s = hud_coordstrz; while (*s) HUlib_addCharToTextLine(&w_coordz, *(s++)); //jff 2/16/98 initialize ammo widget strcpy(hud_ammostr,"AMM "); s = hud_ammostr; while (*s) HUlib_addCharToTextLine(&w_ammo, *(s++)); //jff 2/16/98 initialize health widget strcpy(hud_healthstr,"HEL "); s = hud_healthstr; while (*s) HUlib_addCharToTextLine(&w_health, *(s++)); //jff 2/16/98 initialize armor widget strcpy(hud_armorstr,"ARM "); s = hud_armorstr; while (*s) HUlib_addCharToTextLine(&w_armor, *(s++)); //jff 2/17/98 initialize weapons widget strcpy(hud_weapstr,"WEA "); s = hud_weapstr; while (*s) HUlib_addCharToTextLine(&w_weapon, *(s++)); //jff 2/17/98 initialize keys widget if (!deathmatch) //jff 3/17/98 show frags in deathmatch mode strcpy(hud_keysstr,"KEY "); else strcpy(hud_keysstr,"FRG "); s = hud_keysstr; while (*s) HUlib_addCharToTextLine(&w_keys, *(s++)); //jff 2/17/98 initialize graphic keys widget strcpy(hud_gkeysstr," "); s = hud_gkeysstr; while (*s) HUlib_addCharToTextLine(&w_gkeys, *(s++)); //jff 2/17/98 initialize kills/items/secret widget strcpy(hud_monsecstr,"STS "); s = hud_monsecstr; while (*s) HUlib_addCharToTextLine(&w_monsec, *(s++)); // create the chat widget HUlib_initIText ( &w_chat, HU_INPUTX, HU_INPUTY, hu_font, HU_FONTSTART, hudcolor_chat, &chat_on ); // create the inputbuffer widgets, one per player for (i=0 ; i<MAXPLAYERS ; i++) HUlib_initIText ( &w_inputbuffer[i], 0, 0, 0, 0, hudcolor_chat, &always_off ); // now allow the heads-up display to run headsupactive = true; } // // HU_MoveHud() // // Move the HUD display from distributed to compact mode or vice-versa // // Passed nothing, returns nothing // //jff 3/9/98 create this externally callable to avoid glitch // when menu scatter's HUD due to delay in change of position // void HU_MoveHud(void) { static int ohud_distributed=-1; //jff 3/4/98 move displays around on F5 changing hud_distributed if (hud_distributed!=ohud_distributed) { w_ammo.x = hud_distributed? HU_AMMOX_D : HU_AMMOX; w_ammo.y = hud_distributed? HU_AMMOY_D : HU_AMMOY; w_weapon.x = hud_distributed? HU_WEAPX_D : HU_WEAPX; w_weapon.y = hud_distributed? HU_WEAPY_D : HU_WEAPY; w_keys.x = hud_distributed? HU_KEYSX_D : HU_KEYSX; w_keys.y = hud_distributed? HU_KEYSY_D : HU_KEYSY; w_gkeys.x = hud_distributed? HU_KEYSGX_D : HU_KEYSGX; w_gkeys.y = hud_distributed? HU_KEYSY_D : HU_KEYSY; w_monsec.x = hud_distributed? HU_MONSECX_D : HU_MONSECX; w_monsec.y = hud_distributed? HU_MONSECY_D : HU_MONSECY; w_health.x = hud_distributed? HU_HEALTHX_D : HU_HEALTHX; w_health.y = hud_distributed? HU_HEALTHY_D : HU_HEALTHY; w_armor.x = hud_distributed? HU_ARMORX_D : HU_ARMORX; w_armor.y = hud_distributed? HU_ARMORY_D : HU_ARMORY; } ohud_distributed = hud_distributed; } // // HU_Drawer() // // Draw all the pieces of the heads-up display // // Passed nothing, returns nothing // void HU_Drawer(void) { char *s; player_t *plr; char ammostr[80]; //jff 3/8/98 allow plenty room for dehacked mods char healthstr[80];//jff char armorstr[80]; //jff int i,doit; plr = &players[displayplayer]; // killough 3/7/98 // draw the automap widgets if automap is displayed if (automapmode & am_active) { // map title HUlib_drawTextLine(&w_title, false); //jff 2/16/98 output new coord display // x-coord snprintf(hud_coordstrx,32*sizeof(char),"X: %d", (plr->mo->x)>>FRACBITS); HUlib_clearTextLine(&w_coordx); s = hud_coordstrx; while (*s) HUlib_addCharToTextLine(&w_coordx, *(s++)); HUlib_drawTextLine(&w_coordx, false); //jff 3/3/98 split coord display into x,y,z lines // y-coord snprintf(hud_coordstry,32*sizeof(char),"Y: %d", (plr->mo->y)>>FRACBITS); HUlib_clearTextLine(&w_coordy); s = hud_coordstry; while (*s) HUlib_addCharToTextLine(&w_coordy, *(s++)); HUlib_drawTextLine(&w_coordy, false); //jff 3/3/98 split coord display into x,y,z lines //jff 2/22/98 added z // z-coord snprintf(hud_coordstrz,32*sizeof(char),"Z: %d", (plr->mo->z)>>FRACBITS); HUlib_clearTextLine(&w_coordz); s = hud_coordstrz; while (*s) HUlib_addCharToTextLine(&w_coordz, *(s++)); HUlib_drawTextLine(&w_coordz, false); } // draw the weapon/health/ammo/armor/kills/keys displays if optioned //jff 2/17/98 allow new hud stuff to be turned off // killough 2/21/98: really allow new hud stuff to be turned off COMPLETELY if ( hud_active>0 && // hud optioned on hud_displayed && // hud on from fullscreen key viewheight==SCREENHEIGHT && // fullscreen mode is active !(automapmode & am_active) // automap is not active ) { doit = !(gametic&1); //jff 3/4/98 speed update up for slow systems if (doit) //jff 8/7/98 update every time, avoid lag in update { HU_MoveHud(); // insure HUD display coords are correct // do the hud ammo display // clear the widgets internal line HUlib_clearTextLine(&w_ammo); strcpy(hud_ammostr,"AMM "); if (weaponinfo[plr->readyweapon].ammo == am_noammo) { // special case for weapon with no ammo selected - blank bargraph + N/A strcat(hud_ammostr,"\x7f\x7f\x7f\x7f\x7f\x7f\x7f N/A"); w_ammo.cm = CR_GRAY; } else { int ammo = plr->ammo[weaponinfo[plr->readyweapon].ammo]; int fullammo = plr->maxammo[weaponinfo[plr->readyweapon].ammo]; int ammopct = (100*ammo)/fullammo; int ammobars = ammopct/4; // build the numeric amount init string snprintf(ammostr,sizeof(ammostr),"%d/%d",ammo,fullammo); // build the bargraph string // full bargraph chars for (i=4;i<4+ammobars/4;) hud_ammostr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(ammobars%4) { case 0: break; case 1: hud_ammostr[i++] = 126; break; case 2: hud_ammostr[i++] = 125; break; case 3: hud_ammostr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_ammostr[i++] = 127; hud_ammostr[i] = '\0'; strcat(hud_ammostr,ammostr); // set the display color from the percentage of total ammo held if (ammopct<ammo_red) w_ammo.cm = CR_RED; else if (ammopct<ammo_yellow) w_ammo.cm = CR_GOLD; else w_ammo.cm = CR_GREEN; } // transfer the init string to the widget s = hud_ammostr; while (*s) HUlib_addCharToTextLine(&w_ammo, *(s++)); } // display the ammo widget every frame HUlib_drawTextLine(&w_ammo, false); // do the hud health display if (doit) { int health = plr->health; int healthbars = health>100? 25 : health/4; // clear the widgets internal line HUlib_clearTextLine(&w_health); // build the numeric amount init string snprintf(healthstr,sizeof(healthstr),"%3d",health); // build the bargraph string // full bargraph chars for (i=4;i<4+healthbars/4;) hud_healthstr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(healthbars%4) { case 0: break; case 1: hud_healthstr[i++] = 126; break; case 2: hud_healthstr[i++] = 125; break; case 3: hud_healthstr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_healthstr[i++] = 127; hud_healthstr[i] = '\0'; strcat(hud_healthstr,healthstr); // set the display color from the amount of health posessed if (health<health_red) w_health.cm = CR_RED; else if (health<health_yellow) w_health.cm = CR_GOLD; else if (health<=health_green) w_health.cm = CR_GREEN; else w_health.cm = CR_BLUE; // transfer the init string to the widget s = hud_healthstr; while (*s) HUlib_addCharToTextLine(&w_health, *(s++)); } // display the health widget every frame HUlib_drawTextLine(&w_health, false); // do the hud armor display if (doit) { int armor = plr->armorpoints; int armorbars = armor>100? 25 : armor/4; // clear the widgets internal line HUlib_clearTextLine(&w_armor); // build the numeric amount init string snprintf(armorstr,sizeof(armorstr),"%3d",armor); // build the bargraph string // full bargraph chars for (i=4;i<4+armorbars/4;) hud_armorstr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(armorbars%4) { case 0: break; case 1: hud_armorstr[i++] = 126; break; case 2: hud_armorstr[i++] = 125; break; case 3: hud_armorstr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_armorstr[i++] = 127; hud_armorstr[i] = '\0'; strcat(hud_armorstr,armorstr); // set the display color from the amount of armor posessed if (armor<armor_red) w_armor.cm = CR_RED; else if (armor<armor_yellow) w_armor.cm = CR_GOLD; else if (armor<=armor_green) w_armor.cm = CR_GREEN; else w_armor.cm = CR_BLUE; // transfer the init string to the widget s = hud_armorstr; while (*s) HUlib_addCharToTextLine(&w_armor, *(s++)); } // display the armor widget every frame HUlib_drawTextLine(&w_armor, false); // do the hud weapon display if (doit) { int w; int ammo,fullammo,ammopct; // clear the widgets internal line HUlib_clearTextLine(&w_weapon); i=4; hud_weapstr[i] = '\0'; //jff 3/7/98 make sure ammo goes away // do each weapon that exists in current gamemode for (w=0;w<=wp_supershotgun;w++) //jff 3/4/98 show fists too, why not? { int ok=1; //jff avoid executing for weapons that do not exist switch (gamemode) { case shareware: if (w>=wp_plasma && w!=wp_chainsaw) ok=0; break; case retail: case registered: if (w>=wp_supershotgun) ok=0; break; default: case commercial: break; } if (!ok) continue; ammo = plr->ammo[weaponinfo[w].ammo]; fullammo = plr->maxammo[weaponinfo[w].ammo]; ammopct=0; // skip weapons not currently posessed if (!plr->weaponowned[w]) continue; ammopct = fullammo? (100*ammo)/fullammo : 100; // display each weapon number in a color related to the ammo for it hud_weapstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths if (weaponinfo[w].ammo==am_noammo) //jff 3/14/98 show berserk on HUD hud_weapstr[i++] = plr->powers[pw_strength]? '0'+CR_GREEN : '0'+CR_GRAY; else if (ammopct<ammo_red) hud_weapstr[i++] = '0'+CR_RED; else if (ammopct<ammo_yellow) hud_weapstr[i++] = '0'+CR_GOLD; else hud_weapstr[i++] = '0'+CR_GREEN; hud_weapstr[i++] = '0'+w+1; hud_weapstr[i++] = ' '; hud_weapstr[i] = '\0'; } // transfer the init string to the widget s = hud_weapstr; while (*s) HUlib_addCharToTextLine(&w_weapon, *(s++)); } // display the weapon widget every frame HUlib_drawTextLine(&w_weapon, false); if (doit && hud_active>1) { int k; hud_keysstr[4] = '\0'; //jff 3/7/98 make sure deleted keys go away //jff add case for graphic key display if (!deathmatch && hud_graph_keys) { i=0; hud_gkeysstr[i] = '\0'; //jff 3/7/98 init graphic keys widget string // build text string whose characters call out graphic keys from fontk for (k=0;k<6;k++) { // skip keys not possessed if (!plr->cards[k]) continue; hud_gkeysstr[i++] = '!'+k; // key number plus '!' is char for key hud_gkeysstr[i++] = ' '; // spacing hud_gkeysstr[i++] = ' '; } hud_gkeysstr[i]='\0'; } else // not possible in current code, unless deathmatching, { i=4; hud_keysstr[i] = '\0'; //jff 3/7/98 make sure deleted keys go away // if deathmatch, build string showing top four frag counts if (deathmatch) //jff 3/17/98 show frags, not keys, in deathmatch { int top1=-999,top2=-999,top3=-999,top4=-999; int idx1=-1,idx2=-1,idx3=-1,idx4=-1; int fragcount,m; char numbuf[32]; // scan thru players for (k=0;k<MAXPLAYERS;k++) { // skip players not in game if (!playeringame[k]) continue; fragcount = 0; // compute number of times they've fragged each player // minus number of times they've been fragged by them for (m=0;m<MAXPLAYERS;m++) { if (!playeringame[m]) continue; fragcount += (m!=k)? players[k].frags[m] : -players[k].frags[m]; } // very primitive sort of frags to find top four if (fragcount>top1) { top4=top3; top3=top2; top2 = top1; top1=fragcount; idx4=idx3; idx3=idx2; idx2 = idx1; idx1=k; } else if (fragcount>top2) { top4=top3; top3=top2; top2=fragcount; idx4=idx3; idx3=idx2; idx2=k; } else if (fragcount>top3) { top4=top3; top3=fragcount; idx4=idx3; idx3=k; } else if (fragcount>top4) { top4=fragcount; idx4=k; } } // if the biggest number exists, put it in the init string if (idx1>-1) { snprintf(numbuf,sizeof(numbuf),"%5d",top1); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx1&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the second biggest number exists, put it in the init string if (idx2>-1) { snprintf(numbuf,sizeof(numbuf),"%5d",top2); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx2&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the third biggest number exists, put it in the init string if (idx3>-1) { snprintf(numbuf,sizeof(numbuf),"%5d",top3); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx3&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the fourth biggest number exists, put it in the init string if (idx4>-1) { snprintf(numbuf,sizeof(numbuf),"%5d",top4); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx4&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } hud_keysstr[i] = '\0'; } //jff 3/17/98 end of deathmatch clause else // build alphabetical key display (not used currently) { // scan the keys for (k=0;k<6;k++) { // skip any not possessed by the displayed player's stats if (!plr->cards[k]) continue; // use color escapes to make text in key's color hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths switch(k) { case 0: hud_keysstr[i++] = '0'+CR_BLUE; hud_keysstr[i++] = 'B'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 1: hud_keysstr[i++] = '0'+CR_GOLD; hud_keysstr[i++] = 'Y'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 2: hud_keysstr[i++] = '0'+CR_RED; hud_keysstr[i++] = 'R'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 3: hud_keysstr[i++] = '0'+CR_BLUE; hud_keysstr[i++] = 'B'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; case 4: hud_keysstr[i++] = '0'+CR_GOLD; hud_keysstr[i++] = 'Y'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; case 5: hud_keysstr[i++] = '0'+CR_RED; hud_keysstr[i++] = 'R'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; } hud_keysstr[i]='\0'; } } } } // display the keys/frags line each frame if (hud_active>1) { HUlib_clearTextLine(&w_keys); // clear the widget strings HUlib_clearTextLine(&w_gkeys); // transfer the built string (frags or key title) to the widget s = hud_keysstr; //jff 3/7/98 display key titles/key text or frags while (*s) HUlib_addCharToTextLine(&w_keys, *(s++)); HUlib_drawTextLine(&w_keys, false); //jff 3/17/98 show graphic keys in non-DM only if (!deathmatch) //jff 3/7/98 display graphic keys { // transfer the graphic key text to the widget s = hud_gkeysstr; while (*s) HUlib_addCharToTextLine(&w_gkeys, *(s++)); // display the widget HUlib_drawTextLine(&w_gkeys, false); } } // display the hud kills/items/secret display if optioned if (!hud_nosecrets) { if (hud_active>1 && doit) { // clear the internal widget text buffer HUlib_clearTextLine(&w_monsec); //jff 3/26/98 use ESC not '\' for paths // build the init string with fixed colors snprintf ( hud_monsecstr,80*sizeof(char), "STS \x1b\x36K \x1b\x33%d \x1b\x36M \x1b\x33%d \x1b\x37I \x1b\x33%d/%d \x1b\x35S \x1b\x33%d/%d", plr->killcount,totallive, plr->itemcount,totalitems, plr->secretcount,totalsecret ); // transfer the init string to the widget s = hud_monsecstr; while (*s) HUlib_addCharToTextLine(&w_monsec, *(s++)); } // display the kills/items/secrets each frame, if optioned if (hud_active>1) HUlib_drawTextLine(&w_monsec, false); } } //jff 3/4/98 display last to give priority HU_Erase(); // jff 4/24/98 Erase current lines before drawing current // needed when screen not fullsize //jff 4/21/98 if setup has disabled message list while active, turn it off if (hud_msg_lines<=1) message_list = false; // if the message review not enabled, show the standard message widget if (!message_list) HUlib_drawSText(&w_message); // if the message review is enabled show the scrolling message review if (hud_msg_lines>1 && message_list) HUlib_drawMText(&w_rtext); // display the interactive buffer for chat entry HUlib_drawIText(&w_chat); } // // HU_Erase() // // Erase hud display lines that can be trashed by small screen display // // Passed nothing, returns nothing // void HU_Erase(void) { // erase the message display or the message review display if (!message_list) HUlib_eraseSText(&w_message); else HUlib_eraseMText(&w_rtext); // erase the interactive text buffer for chat entry HUlib_eraseIText(&w_chat); // erase the automap title HUlib_eraseTextLine(&w_title); } // // HU_Ticker() // // Update the hud displays once per frame // // Passed nothing, returns nothing // static boolean bsdown; // Is backspace down? static int bscounter; void HU_Ticker(void) { int i, rc; char c; // tick down message counter if message is up if (message_counter && !--message_counter) { message_on = false; message_nottobefuckedwith = false; } if (bsdown && bscounter++ > 9) { HUlib_keyInIText(&w_chat, (unsigned char)key_backspace); bscounter = 8; } // if messages on, or "Messages Off" is being displayed // this allows the notification of turning messages off to be seen if (showMessages || message_dontfuckwithme) { // display message if necessary if ((plr->message && !message_nottobefuckedwith) || (plr->message && message_dontfuckwithme)) { //post the message to the message widget HUlib_addMessageToSText(&w_message, 0, plr->message); //jff 2/26/98 add message to refresh text widget too HUlib_addMessageToMText(&w_rtext, 0, plr->message); // clear the message to avoid posting multiple times plr->message = 0; // note a message is displayed message_on = true; // start the message persistence counter message_counter = HU_MSGTIMEOUT; // transfer "Messages Off" exception to the "being displayed" variable message_nottobefuckedwith = message_dontfuckwithme; // clear the flag that "Messages Off" is being posted message_dontfuckwithme = 0; } } // check for incoming chat characters if (netgame) { for (i=0; i<MAXPLAYERS; i++) { if (!playeringame[i]) continue; if (i != consoleplayer && (c = players[i].cmd.chatchar)) { if (c <= HU_BROADCAST) chat_dest[i] = c; else { if (c >= 'a' && c <= 'z') c = (char) shiftxform[(unsigned char) c]; rc = HUlib_keyInIText(&w_inputbuffer[i], c); if (rc && c == KEY_ENTER) { if (w_inputbuffer[i].l.len && (chat_dest[i] == consoleplayer+1 || chat_dest[i] == HU_BROADCAST)) { HUlib_addMessageToSText(&w_message, player_names[i], w_inputbuffer[i].l.l); message_nottobefuckedwith = true; message_on = true; message_counter = HU_MSGTIMEOUT; if ( gamemode == commercial ) S_StartSound(0, sfx_radio); else S_StartSound(0, sfx_tink); } HUlib_resetIText(&w_inputbuffer[i]); } } players[i].cmd.chatchar = 0; } } } } #define QUEUESIZE 128 static char chatchars[QUEUESIZE]; static int head = 0; static int tail = 0; // // HU_queueChatChar() // // Add an incoming character to the circular chat queue // // Passed the character to queue, returns nothing // void HU_queueChatChar(char c) { if (((head + 1) & (QUEUESIZE-1)) == tail) { plr->message = HUSTR_MSGU; } else { chatchars[head] = c; head = (head + 1) & (QUEUESIZE-1); } } // // HU_dequeueChatChar() // // Remove the earliest added character from the circular chat queue // // Passed nothing, returns the character dequeued // char HU_dequeueChatChar(void) { char c; if (head != tail) { c = chatchars[tail]; tail = (tail + 1) & (QUEUESIZE-1); } else { c = 0; } return c; } // // HU_Responder() // // Responds to input events that affect the heads up displays // // Passed the event to respond to, returns true if the event was handled // boolean HU_Responder(event_t *ev) { static char lastmessage[HU_MAXLINELENGTH+1]; const char* macromessage; // CPhipps - const char* boolean eatkey = false; static boolean shiftdown = false; static boolean altdown = false; unsigned char c; int i; int numplayers; static int num_nobrainers = 0; numplayers = 0; for (i=0 ; i<MAXPLAYERS ; i++) numplayers += playeringame[i]; if (ev->data1 == key_shift) { shiftdown = ev->type == ev_keydown; return false; } else if (ev->data1 == key_alt) { altdown = ev->type == ev_keydown; return false; } else if (ev->data1 == key_backspace) { bsdown = ev->type == ev_keydown; bscounter = 0; } if (ev->type != ev_keydown) return false; if (!chat_on) { if (ev->data1 == key_enter) // phares { #ifndef INSTRUMENTED // never turn on message review if INSTRUMENTED defined if (hud_msg_lines>1) // it posts multi-line messages that will trash { if (message_list) HU_Erase(); //jff 4/28/98 erase behind messages message_list = !message_list; //jff 2/26/98 toggle list of messages } #endif if (!message_list) // if not message list, refresh message { message_on = true; message_counter = HU_MSGTIMEOUT; } eatkey = true; }//jff 2/26/98 no chat if message review is displayed else if (!message_list && netgame && ev->data1 == key_chat) { eatkey = chat_on = true; HUlib_resetIText(&w_chat); HU_queueChatChar(HU_BROADCAST); }//jff 2/26/98 no chat if message review is displayed // killough 10/02/98: no chat if demo playback else if (!demoplayback && !message_list && netgame && numplayers > 2) { for (i=0; i<MAXPLAYERS ; i++) { if (ev->data1 == destination_keys[i]) { if (playeringame[i] && i!=consoleplayer) { eatkey = chat_on = true; HUlib_resetIText(&w_chat); HU_queueChatChar((char)(i+1)); break; } else if (i == consoleplayer) { num_nobrainers++; if (num_nobrainers < 3) plr->message = HUSTR_TALKTOSELF1; else if (num_nobrainers < 6) plr->message = HUSTR_TALKTOSELF2; else if (num_nobrainers < 9) plr->message = HUSTR_TALKTOSELF3; else if (num_nobrainers < 32) plr->message = HUSTR_TALKTOSELF4; else plr->message = HUSTR_TALKTOSELF5; } } } } }//jff 2/26/98 no chat functions if message review is displayed else if (!message_list) { c = ev->data1; // send a macro if (altdown) { c = c - '0'; if (c > 9) return false; macromessage = chat_macros[c]; // kill last message with a '\n' HU_queueChatChar((char)key_enter); // DEBUG!!! // phares // send the macro message while (*macromessage) HU_queueChatChar(*macromessage++); HU_queueChatChar((char)key_enter); // phares // leave chat mode and notify that it was sent chat_on = false; strcpy(lastmessage, chat_macros[c]); plr->message = lastmessage; eatkey = true; } else { if (shiftdown || (c >= 'a' && c <= 'z')) c = shiftxform[c]; eatkey = HUlib_keyInIText(&w_chat, c); if (eatkey) HU_queueChatChar(c); if (c == key_enter) // phares { chat_on = false; if (w_chat.l.len) { strcpy(lastmessage, w_chat.l.l); plr->message = lastmessage; } } else if (c == key_escape) // phares chat_on = false; } } return eatkey; }