Previous 15994 Revisions Next

r3368 Wednesday 1st October, 2008 at 22:51:07 UTC by Firewave
Removed obsolete files
[src/emu/machine]laserdsc.c
[src/emu/sound]namcona.c namcona.h

src/emu/machine/laserdsc.c
r3367r3368
1/*************************************************************************
2
3    laserdsc.c
4
5    Generic laserdisc support.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10*************************************************************************/
11
12#include "driver.h"
13#include "laserdsc.h"
14#include "avcomp.h"
15#include "streams.h"
16#include "vbiparse.h"
17#include "config.h"
18#include "sound/custom.h"
19
20
21
22/***************************************************************************
23    DEBUGGING
24***************************************************************************/
25
26#define PRINTF_COMMANDS            1
27
28#define LOG_POSITION(x)            /*printf x*/
29
30#define CMDPRINTF(x)            do { if (PRINTF_COMMANDS) mame_printf_debug x; } while (0)
31
32
33
34/***************************************************************************
35    CONSTANTS
36***************************************************************************/
37
38/* fractional track handling */
39#define FRACBITS               12
40#define FRAC_ONE               (1 << FRACBITS)
41#define INT_TO_FRAC(x)            ((x) << FRACBITS)
42#define FRAC_TO_INT(x)            ((x) >> FRACBITS)
43
44/* general laserdisc playback states */
45enum _playstate
46{
47   LASERDISC_EJECTED,                  /* no disc present */
48   LASERDISC_EJECTING,                  /* in the process of ejecting */
49   LASERDISC_LOADED,                  /* disc just loaded */
50   LASERDISC_LOADING,                  /* in the process of loading */
51   LASERDISC_PARKED,                  /* disc loaded, not playing, head on parked position */
52   LASERDISC_SPINUP,                  /* disc loaded, spinning up to speed */
53
54   LASERDISC_SEARCHING_FRAME,            /* searching (seeking) to a new frame */
55   LASERDISC_SEARCH_FINISHED,            /* finished searching; same as stopped */
56
57   LASERDISC_STOPPED,                  /* stopped (paused) with video visible and no sound */
58   LASERDISC_AUTOSTOPPED,               /* autostopped; same as stopped */
59
60   LASERDISC_PLAYING_FORWARD,            /* playing at 1x in the forward direction */
61   LASERDISC_PLAYING_REVERSE,            /* playing at 1x in the reverse direction */
62   LASERDISC_PLAYING_SLOW_FORWARD,         /* playing forward slowly */
63   LASERDISC_PLAYING_SLOW_REVERSE,         /* playing backward slowly */
64   LASERDISC_PLAYING_FAST_FORWARD,         /* playing fast forward */
65   LASERDISC_PLAYING_FAST_REVERSE,         /* playing fast backward */
66   LASERDISC_STEPPING_FORWARD,            /* stepping forward */
67   LASERDISC_STEPPING_REVERSE,            /* stepping backward */
68   LASERDISC_SCANNING_FORWARD,            /* scanning forward at the scan rate */
69   LASERDISC_SCANNING_REVERSE            /* scanning backward at the scan rate */
70};
71typedef enum _playstate playstate;
72
73/* generic states and configuration */
74#define FRAMEFLAG_PREV_SAME_FRAME   0x01
75#define FRAMEFLAG_NEXT_SAME_FRAME   0x02
76
77#define AUDIO_CH1_ENABLE         0x01
78#define AUDIO_CH2_ENABLE         0x02
79#define AUDIO_EXPLICIT_MUTE         0x04
80#define AUDIO_IMPLICIT_MUTE         0x08
81#define AUDIO_SQUELCH_OVERRIDE      0x10
82
83#define VIDEO_ENABLE            0x01
84#define VIDEO_EXPLICIT_MUTE         0x02
85#define VIDEO_IMPLICIT_MUTE         0x04
86
87#define DISPLAY_ENABLE            0x01
88
89#define NULL_TARGET_FRAME         0               /* frame 0 indicates no target */
90#define ONE_TRACK               INT_TO_FRAC(1)      /* a single track, or track #1 */
91#define STOP_SPEED               INT_TO_FRAC(0)      /* no movement */
92#define PLAY_SPEED               INT_TO_FRAC(1)      /* regular playback speed */
93
94#define GENERIC_SPINUP_TIME         (attotime_make(5, 0))
95#define GENERIC_LOAD_TIME         (attotime_make(10, 0))
96#define GENERIC_RESET_SPEED         INT_TO_FRAC(5000)
97
98/* Pioneer PR-7820 specific states */
99#define PR7820_MODE_MANUAL         0
100#define PR7820_MODE_AUTOMATIC      1
101#define PR7820_MODE_PROGRAM         2
102
103#define PR7820_SEARCH_SPEED         INT_TO_FRAC(5000)
104
105/* Pioneer PR-8210/LD-V1100 specific states */
106#define PR8210_SCAN_SPEED         (INT_TO_FRAC(2000) / 30)
107#define PR8210_FAST_SPEED         (PLAY_SPEED * 3)
108#define PR8210_SLOW_SPEED         (PLAY_SPEED / 5)
109#define PR8210_STEP_SPEED         (PLAY_SPEED / 7)
110#define PR8210_SEARCH_SPEED         INT_TO_FRAC(5000)
111
112/* Simutrek Special specific states */
113#define SIMUTREK_SCAN_SPEED         PR8210_SCAN_SPEED
114#define SIMUTREK_FAST_SPEED         PR8210_FAST_SPEED
115#define SIMUTREK_SLOW_SPEED         PR8210_SLOW_SPEED
116#define SIMUTREK_STEP_SPEED         PR8210_STEP_SPEED
117#define SIMUTREK_SEARCH_SPEED      PR8210_SEARCH_SPEED
118
119/* Pioneer LD-V1000 specific states */
120#define LDV1000_MODE_STATUS         0
121#define LDV1000_MODE_GET_FRAME      1
122#define LDV1000_MODE_GET_1ST      2
123#define LDV1000_MODE_GET_2ND      3
124#define LDV1000_MODE_GET_RAM      4
125
126#define LDV1000_SCAN_SPEED         (INT_TO_FRAC(2000) / 30)
127#define LDV1000_SEARCH_SPEED      INT_TO_FRAC(5000)
128
129/* Sony LDP-1450 specific states */
130#define LDP1450_SCAN_SPEED         (INT_TO_FRAC(2000) / 30)
131#define LDP1450_FAST_SPEED         (PLAY_SPEED * 3)
132#define LDP1450_SLOW_SPEED         (PLAY_SPEED / 5)
133#define LDP1450_STEP_SPEED         (PLAY_SPEED / 7)
134#define LDP1450_SEARCH_SPEED      INT_TO_FRAC(5000)
135
136/* Philips 22VP932 specific states */
137#define VP932_SCAN_SPEED         (INT_TO_FRAC(2000) / 30)
138#define VP932_FAST_SPEED         (PLAY_SPEED * 3)
139#define VP932_SLOW_SPEED         (PLAY_SPEED / 5)
140#define VP932_STEP_SPEED         (PLAY_SPEED / 7)
141#define VP932_SEARCH_SPEED         INT_TO_FRAC(5000)
142
143
144
145/***************************************************************************
146    TYPE DEFINITIONS
147***************************************************************************/
148
149/* PR-7820-specific data */
150typedef struct _pr7820_info pr7820_info;
151struct _pr7820_info
152{
153   UINT8            mode;               /* current mode */
154   UINT32            curpc;               /* current PC for automatic execution */
155   INT32            configspeed;         /* configured speed */
156   UINT32            activereg;            /* active register index */
157   UINT8            ram[1024];            /* RAM */
158};
159
160
161/* PR8210-specific data */
162typedef struct _pr8210_info pr8210_info;
163struct _pr8210_info
164{
165   UINT8            mode;               /* current mode */
166   UINT8            lastcommand;         /* last command byte received */
167   UINT16            accumulator;         /* bit accumulator */
168   attotime         lastbittime;         /* time of last bit received */
169   attotime         firstbittime;         /* time of first bit in command */
170   UINT8            seekstate;            /* state of the seek command */
171};
172
173/* Simutrek-specific data */
174typedef struct _simutrek_info simutrek_info;
175struct _simutrek_info
176{
177   UINT8            mode;               /* current mode */
178   UINT8            lastcommand;         /* last command byte received */
179   UINT16            accumulator;         /* bit accumulator */
180   attotime         lastbittime;         /* time of last bit received */
181   attotime         firstbittime;         /* time of first bit in command */
182   UINT8            seekstate;            /* state of the seek command */
183   UINT8            cmdcnt;               /* counter for multi-byte command */
184   UINT8            cmdbytes[3];         /* storage for multi-byte command */
185   void            (*cmd_ack_callback)(void); /* callback to clear game command write flag */
186};
187
188
189/* LD-V1000-specific data */
190typedef struct _ldv1000_info ldv1000_info;
191struct _ldv1000_info
192{
193   UINT8            mode;               /* current mode */
194   UINT32            activereg;            /* active register index */
195   UINT8            ram[1024];            /* RAM */
196   UINT32            readpos;            /* current read position */
197   UINT32            readtotal;            /* current read position */
198   UINT8            readbuf[256];         /* temporary read buffer */
199};
200
201
202/* LDP-1450-specific data */
203typedef struct _ldp1450_info ldp1450_info;
204struct _ldp1450_info
205{
206   UINT32            readpos;            /* current read position */
207   UINT32            readtotal;            /* current read position */
208   UINT8            readbuf[256];         /* temporary read buffer */
209};
210
211
212/* 22VP932-specific data */
213typedef struct _vp932_info vp932_info;
214struct _vp932_info
215{
216   UINT8            incount;            /* number of pending bytes accumulated */
217   UINT8            inbuffer[8];         /* input data */
218   UINT8            outcount;            /* number of pending bytes to send */
219   UINT8            outbuffer[8];         /* output data */
220};
221
222
223/* generic data */
224typedef struct _laserdisc_state laserdisc_state;
225struct _laserdisc_state
226{
227   /* general config */
228   laserdisc_config   config;               /* copy of the inline config */
229
230   /* disc parameters */
231   chd_file *         disc;               /* handle to the disc itself */
232   av_codec_decompress_config avconfig;      /* decompression configuration */
233   UINT8            readpending;         /* true if a read is pending */
234   UINT32            maxfractrack;         /* maximum track number */
235   UINT32            fieldnum;            /* field number (0 or 1) */
236
237   /* video data */
238   bitmap_t *         videoframe[3];         /* currently cached frames */
239   bitmap_t *         videovisframe[3];      /* wrapper around videoframe with only visible lines */
240   UINT8            videofields[3];         /* number of fields in each frame */
241   UINT32            videoframenum[3];      /* frame number contained in each frame */
242   UINT8            videoindex;            /* index of the current video buffer */
243   bitmap_t *         emptyframe;            /* blank frame */
244   bitmap_t         videotarget;         /* fake target bitmap for decompression */
245
246   /* audio data */
247   INT16 *            audiobuffer[2];         /* buffer for audio samples */
248   UINT32            audiobufsize;         /* size of buffer */
249   UINT32            audiobufin;            /* input index */
250   UINT32            audiobufout;         /* output index */
251   UINT32            audiocursamples;      /* current samples this track */
252   UINT32            audiomaxsamples;      /* maximum samples per track */
253   int               audiocustom;         /* custom sound index */
254   int               samplerate;            /* playback samplerate */
255
256   /* metadata */
257   vbi_metadata      metadata[2];         /* metadata parsed from the stream, for each field */
258   int               last_frame;            /* last seen frame number */
259   int               last_chapter;         /* last seen chapter number */
260
261   /* core states */
262   playstate         state;               /* current playback state */
263   UINT8            video;               /* video state: bit 0 = on/off */
264   UINT8            audio;               /* audio state: bit 0 = audio 1, bit 1 = audio 2 */
265   UINT8            display;            /* display state: bit 0 = on/off */
266   attotime         lastvsynctime;         /* time of the last vsync */
267
268   /* deferred states */
269   attotime         holdfinished;         /* time when current state will advance */
270   UINT8            postholdstate;         /* state to switch into after holding */
271   INT32            postholdfracspeed;      /* speed after the hold */
272
273   /* input data */
274   UINT8            datain;               /* current input data value */
275   UINT8            linein[LASERDISC_INPUT_LINES]; /* current input line state */
276
277   /* output data */
278   UINT8            dataout;            /* current output data value */
279   UINT8            lineout[LASERDISC_OUTPUT_LINES]; /* current output line state */
280
281   /* command and parameter buffering */
282   UINT8            command;            /* current command */
283   INT32            parameter;            /* command parameter */
284
285   /* playback/search/scan speeds */
286   INT32            curfracspeed;         /* current speed the head is moving */
287   INT32            curfractrack;         /* current track */
288   INT32            targetframe;         /* target frame (0 means no target) */
289
290   /* video updating */
291   UINT8            videoenable;         /* is video enabled? */
292   render_texture *   videotex;            /* texture for the video */
293   UINT8            overenable;            /* is the overlay enabled? */
294   bitmap_t *         overbitmap[2];         /* overlay bitmaps */
295   int               overindex;            /* index of the overlay bitmap */
296   render_texture *   overtex;            /* texture for the overlay */
297
298   /* debugging */
299   char            text[100];            /* buffer for the state */
300   UINT8            lastbackslash;         /* state of last backslash key check */
301
302   /* filled in by player-specific init */
303   void             (*writedata)(laserdisc_state *ld, UINT8 prev, UINT8 new); /* write callback */
304   void             (*writeline[LASERDISC_INPUT_LINES])(laserdisc_state *ld, UINT8 new); /* write line callback */
305   UINT8            (*readdata)(laserdisc_state *ld);   /* status callback */
306   UINT8            (*readline[LASERDISC_OUTPUT_LINES])(laserdisc_state *ld); /* read line callback */
307   void            (*statechanged)(laserdisc_state *ld, UINT8 oldstate); /* state changed callback */
308
309   /* some player-specific data */
310   union
311   {
312      pr7820_info      pr7820;               /* PR-7820-specific info */
313      pr8210_info      pr8210;               /* PR-8210-specific info */
314      simutrek_info   simutrek;            /* Simutrek-specific info */
315      ldv1000_info    ldv1000;            /* LD-V1000-specific info */
316      ldp1450_info    ldp1450;            /* LDP-1450-specific info */
317      vp932_info       vp932;               /* 22VP932-specific info */
318   } u;
319};
320
321
322/* sound callback info */
323typedef struct _sound_token sound_token;
324struct _sound_token
325{
326   sound_stream *      stream;
327   laserdisc_state *   ld;
328};
329
330
331
332/***************************************************************************
333    FUNCTION PROTOTYPES
334***************************************************************************/
335
336/* generic helper functions */
337static int update_position(laserdisc_state *ld);
338static void read_track_data(laserdisc_state *ld);
339static void process_track_data(const device_config *device);
340static void fake_metadata(UINT32 track, UINT8 which, vbi_metadata *metadata);
341static void render_display(UINT16 *videodata, UINT32 rowpixels, UINT32 width, int frame);
342static void *custom_start(int clock, const custom_sound_interface *config);
343static void custom_stream_callback(void *param, stream_sample_t **inputs, stream_sample_t **outputs, int samples);
344static void configuration_load(running_machine *machine, int config_type, xml_data_node *parentnode);
345static void configuration_save(running_machine *machine, int config_type, xml_data_node *parentnode);
346
347/* Pioneer PR-7820 implementation */
348static void pr7820_init(laserdisc_state *ld);
349static void pr7820_soft_reset(laserdisc_state *ld);
350static void pr7820_enter_w(laserdisc_state *ld, UINT8 data);
351static UINT8 pr7820_ready_r(laserdisc_state *ld);
352static UINT8 pr7820_status_r(laserdisc_state *ld);
353
354/* Pioneer PR-8210 implementation */
355static void pr8210_init(laserdisc_state *ld);
356static void pr8210_soft_reset(laserdisc_state *ld);
357static void pr8210_command(laserdisc_state *ld);
358static void pr8210_control_w(laserdisc_state *ld, UINT8 data);
359
360/* Simutrek modified players implementation */
361static void simutrek_init(laserdisc_state *ld);
362static void simutrek_soft_reset(laserdisc_state *ld);
363static void simutrek_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data);
364static UINT8 simutrek_status_r(laserdisc_state *ld);
365
366/* Pioneer LDV-1000 implementation */
367static void ldv1000_init(laserdisc_state *ld);
368static void ldv1000_soft_reset(laserdisc_state *ld);
369static void ldv1000_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data);
370static UINT8 ldv1000_status_strobe_r(laserdisc_state *ld);
371static UINT8 ldv1000_command_strobe_r(laserdisc_state *ld);
372static UINT8 ldv1000_status_r(laserdisc_state *ld);
373
374/* Sony LDP-1450 implementation */
375static void ldp1450_init(laserdisc_state *ld);
376static void ldp1450_soft_reset(laserdisc_state *ld);
377static void ldp1450_compute_status(laserdisc_state *ld);
378static void ldp1450_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data);
379static UINT8 ldp1450_data_avail_r(laserdisc_state *ld);
380static UINT8 ldp1450_data_r(laserdisc_state *ld);
381static void ldp1450_state_changed(laserdisc_state *ld, UINT8 oldstate);
382
383/* Philips 22VP932 implementation */
384static void vp932_init(laserdisc_state *ld);
385static void vp932_soft_reset(laserdisc_state *ld);
386static void vp932_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data);
387static UINT8 vp932_data_avail_r(laserdisc_state *ld);
388static UINT8 vp932_data_r(laserdisc_state *ld);
389static void vp932_state_changed(laserdisc_state *ld, UINT8 oldstate);
390
391
392
393/***************************************************************************
394    GLOBAL VARIABLES
395***************************************************************************/
396
397const custom_sound_interface laserdisc_custom_interface =
398{
399   custom_start
400};
401
402static const UINT8 numberfont[10][8] =
403{
404   {
405      0x30,   // ..xx....
406      0x48,   // .x..x...
407      0x84,   // x....x..
408      0x84,   // x....x..
409      0x84,   // x....x..
410      0x48,   // .x..x...
411      0x30   // ..xx....
412   },
413   {
414      0x10,   // ...x....
415      0x30,   // ..xx....
416      0x50,   // .x.x....
417      0x10,   // ...x....
418      0x10,   // ...x....
419      0x10,   // ...x....
420      0x7c   // .xxxxx..
421   },
422   {
423      0x78,   // .xxxx...
424      0x84,   // x....x..
425      0x04,   // .....x..
426      0x38,   // ..xxx...
427      0x40,   // .x......
428      0x80,   // x.......
429      0xfc   // xxxxxx..
430   },
431   {
432      0x78,   // .xxxx...
433      0x84,   // x....x..
434      0x04,   // .....x..
435      0x38,   // ..xxx...
436      0x04,   // .....x..
437      0x84,   // x....x..
438      0x78   // .xxxx...
439   },
440   {
441      0x08,   // ....x...
442      0x18,   // ...xx...
443      0x28,   // ..x.x...
444      0x48,   // .x..x...
445      0xfc,   // xxxxxx..
446      0x08,   // ....x...
447      0x08   // ....x...
448   },
449   {
450      0xfc,   // xxxxxx..
451      0x80,   // x.......
452      0x80,   // x.......
453      0xf8,   // xxxxx...
454      0x04,   // .....x..
455      0x84,   // x....x..
456      0x78   // .xxxx...
457   },
458   {
459      0x38,   // ..xxx...
460      0x40,   // .x......
461      0x80,   // x.......
462      0xf8,   // xxxxx...
463      0x84,   // x....x..
464      0x84,   // x....x..
465      0x78   // .xxxx...
466   },
467   {
468      0xfc,   // xxxxxx..
469      0x04,   // .....x..
470      0x08,   // ....x...
471      0x10,   // ...x....
472      0x20,   // ..x.....
473      0x20,   // ..x.....
474      0x20   // ..x.....
475   },
476   {
477      0x78,   // .xxxx...
478      0x84,   // x....x..
479      0x84,   // x....x..
480      0x78,   // .xxxx...
481      0x84,   // x....x..
482      0x84,   // x....x..
483      0x78   // .xxxx...
484   },
485   {
486      0x78,   // .xxxx..
487      0x84,   // x....x.
488      0x84,   // x....x.
489      0x7c,   // .xxxxx.
490      0x04,   // .....x.
491      0x08,   // ....x..
492      0x70,   // .xxx...
493   }
494};
495
496
497
498/***************************************************************************
499    INLINE FUNCTIONS
500***************************************************************************/
501
502/*-------------------------------------------------
503    get_safe_token - makes sure that the passed
504    in device is, in fact, a laserdisc device
505-------------------------------------------------*/
506
507INLINE laserdisc_state *get_safe_token(const device_config *device)
508{
509   assert(device != NULL);
510   assert(device->token != NULL);
511   assert(device->type == LASERDISC);
512
513   return (laserdisc_state *)device->token;
514}
515
516
517/*-------------------------------------------------
518    audio_channel_active - return TRUE if the
519    given audio channel should be output
520-------------------------------------------------*/
521
522INLINE int audio_channel_active(laserdisc_state *ld, int channel)
523{
524   int result = (ld->audio >> channel) & 1;
525
526   /* apply muting */
527   if (ld->audio & (AUDIO_EXPLICIT_MUTE | AUDIO_IMPLICIT_MUTE))
528      result = 0;
529
530   /* implicitly muted during some states */
531   switch (ld->state)
532   {
533      case LASERDISC_EJECTED:
534      case LASERDISC_EJECTING:
535      case LASERDISC_LOADING:
536      case LASERDISC_SPINUP:
537      case LASERDISC_PARKED:
538      case LASERDISC_LOADED:
539      case LASERDISC_SEARCHING_FRAME:
540      case LASERDISC_SEARCH_FINISHED:
541      case LASERDISC_STOPPED:
542      case LASERDISC_AUTOSTOPPED:
543      case LASERDISC_PLAYING_SLOW_FORWARD:
544      case LASERDISC_PLAYING_SLOW_REVERSE:
545      case LASERDISC_PLAYING_FAST_FORWARD:
546      case LASERDISC_PLAYING_FAST_REVERSE:
547      case LASERDISC_SCANNING_FORWARD:
548      case LASERDISC_SCANNING_REVERSE:
549      case LASERDISC_STEPPING_FORWARD:
550      case LASERDISC_STEPPING_REVERSE:
551         result = 0;
552         break;
553
554      default:
555         break;
556   }
557   if (ld->audio & AUDIO_SQUELCH_OVERRIDE)
558      result = 1;
559   return result;
560}
561
562
563/*-------------------------------------------------
564    video_active - return TRUE if the video should
565    be output
566-------------------------------------------------*/
567
568INLINE int video_active(laserdisc_state *ld)
569{
570   int result = ld->video & VIDEO_ENABLE;
571
572   /* apply muting */
573   if (ld->video & (VIDEO_EXPLICIT_MUTE | VIDEO_IMPLICIT_MUTE))
574      result = 0;
575
576   /* implicitly muted during some states */
577   switch (ld->state)
578   {
579      case LASERDISC_EJECTED:
580      case LASERDISC_EJECTING:
581      case LASERDISC_LOADING:
582      case LASERDISC_SPINUP:
583      case LASERDISC_PARKED:
584      case LASERDISC_LOADED:
585      case LASERDISC_SEARCHING_FRAME:
586         result = 0;
587         break;
588
589      default:
590         break;
591   }
592   return result;
593}
594
595
596/*-------------------------------------------------
597    laserdisc_ready - return TRUE if the
598    disc is not in a transient state
599-------------------------------------------------*/
600
601INLINE int laserdisc_ready(laserdisc_state *ld)
602{
603   switch (ld->state)
604   {
605      case LASERDISC_EJECTED:
606      case LASERDISC_EJECTING:
607      case LASERDISC_LOADING:
608      case LASERDISC_SPINUP:
609      case LASERDISC_PARKED:
610         return FALSE;
611
612      case LASERDISC_LOADED:
613      case LASERDISC_SEARCHING_FRAME:
614      case LASERDISC_SEARCH_FINISHED:
615      case LASERDISC_STOPPED:
616      case LASERDISC_AUTOSTOPPED:
617      case LASERDISC_PLAYING_FORWARD:
618      case LASERDISC_PLAYING_REVERSE:
619      case LASERDISC_PLAYING_SLOW_FORWARD:
620      case LASERDISC_PLAYING_SLOW_REVERSE:
621      case LASERDISC_PLAYING_FAST_FORWARD:
622      case LASERDISC_PLAYING_FAST_REVERSE:
623      case LASERDISC_STEPPING_FORWARD:
624      case LASERDISC_STEPPING_REVERSE:
625      case LASERDISC_SCANNING_FORWARD:
626      case LASERDISC_SCANNING_REVERSE:
627         return TRUE;
628   }
629   fatalerror("Unexpected state in laserdisc_ready\n");
630}
631
632
633/*-------------------------------------------------
634    laserdisc_active - return TRUE if the
635    disc is in a playing/spinning state
636-------------------------------------------------*/
637
638INLINE int laserdisc_active(laserdisc_state *ld)
639{
640   switch (ld->state)
641   {
642      case LASERDISC_EJECTED:
643      case LASERDISC_EJECTING:
644      case LASERDISC_LOADED:
645      case LASERDISC_LOADING:
646      case LASERDISC_SPINUP:
647      case LASERDISC_PARKED:
648         return FALSE;
649
650      case LASERDISC_SEARCHING_FRAME:
651      case LASERDISC_SEARCH_FINISHED:
652      case LASERDISC_STOPPED:
653      case LASERDISC_AUTOSTOPPED:
654      case LASERDISC_PLAYING_FORWARD:
655      case LASERDISC_PLAYING_REVERSE:
656      case LASERDISC_PLAYING_SLOW_FORWARD:
657      case LASERDISC_PLAYING_SLOW_REVERSE:
658      case LASERDISC_PLAYING_FAST_FORWARD:
659      case LASERDISC_PLAYING_FAST_REVERSE:
660      case LASERDISC_STEPPING_FORWARD:
661      case LASERDISC_STEPPING_REVERSE:
662      case LASERDISC_SCANNING_FORWARD:
663      case LASERDISC_SCANNING_REVERSE:
664         return TRUE;
665   }
666   fatalerror("Unexpected state in laserdisc_ready\n");
667}
668
669
670/*-------------------------------------------------
671    set_state - configure the current playback
672    state
673-------------------------------------------------*/
674
675INLINE void set_state(laserdisc_state *ld, playstate state, INT32 fracspeed, INT32 targetframe)
676{
677   ld->holdfinished.seconds = 0;
678   ld->holdfinished.attoseconds = 0;
679   ld->state = state;
680   ld->curfracspeed = fracspeed;
681   ld->targetframe = targetframe;
682}
683
684
685/*-------------------------------------------------
686    set_hold_state - configure a hold time and
687    a playback state to follow
688-------------------------------------------------*/
689
690INLINE void set_hold_state(laserdisc_state *ld, attotime holdtime, playstate state, INT32 fracspeed)
691{
692   ld->holdfinished = attotime_add(timer_get_time(), holdtime);
693   ld->postholdstate = state;
694   ld->postholdfracspeed = fracspeed;
695}
696
697
698/*-------------------------------------------------
699    reset_tracknum - reset the current track
700    number to 1 and clear out other state
701-------------------------------------------------*/
702
703INLINE void reset_tracknum(laserdisc_state *ld)
704{
705   ld->curfractrack = ONE_TRACK;
706   ld->last_frame = 0;
707   ld->last_chapter = 0;
708}
709
710
711/*-------------------------------------------------
712    add_to_current_track - add a value to the
713    current track, stopping if we hit the min or
714    max
715-------------------------------------------------*/
716
717INLINE int add_to_current_track(laserdisc_state *ld, INT32 delta)
718{
719   ld->curfractrack += delta;
720   if (ld->curfractrack < ONE_TRACK)
721   {
722      ld->curfractrack = ONE_TRACK;
723      return TRUE;
724   }
725   else if (ld->curfractrack >= ld->maxfractrack - ONE_TRACK)
726   {
727      ld->curfractrack = ld->maxfractrack - ONE_TRACK;
728      return TRUE;
729   }
730   return FALSE;
731}
732
733
734/*-------------------------------------------------
735    frame_from_metadata - return the frame number
736    encoded in the metadata, if present, or -1
737-------------------------------------------------*/
738
739INLINE int frame_from_metadata(const vbi_metadata *metadata)
740{
741   UINT32 data;
742
743   if ((metadata->line1718 & 0xf80000) == 0xf80000)
744      data = metadata->line1718 & 0x7ffff;
745   else if (metadata->line1718 == 0x88ffff)
746      return 0;
747   else if (metadata->line1718 == 0x80eeee)
748      return 99999;
749   else
750      return -1;
751
752   return (((data >> 16) & 0x0f) * 10000) + (((data >> 12) & 0x0f) * 1000) + (((data >> 8) & 0x0f) * 100) + (((data >> 4) & 0x0f) * 10) + (data & 0x0f);
753}
754
755
756/*-------------------------------------------------
757    chapter_from_metadata - return the chapter
758    number encoded in the metadata, if present,
759    or -1
760-------------------------------------------------*/
761
762INLINE int chapter_from_metadata(const vbi_metadata *metadata)
763{
764   UINT32 data;
765
766   if ((metadata->line1718 & 0xf00fff) == 0x800ddd)
767      data = metadata->line1718 & 0x7f000;
768   else
769      return -1;
770
771   return (((data >> 16) & 0x0f) * 10) + ((data >> 12) & 0x0f);
772}
773
774
775/*-------------------------------------------------
776    read_16bits_from_ram_be - read 16 bits from
777    player RAM in big-endian format
778-------------------------------------------------*/
779
780INLINE UINT16 read_16bits_from_ram_be(UINT8 *ram, UINT32 offset)
781{
782   return (ram[offset + 0] << 8) | ram[offset + 1];
783}
784
785
786/*-------------------------------------------------
787    write_16bits_to_ram_be - write 16 bits to
788    player RAM in big endian format
789-------------------------------------------------*/
790
791INLINE void write_16bits_to_ram_be(UINT8 *ram, UINT32 offset, UINT16 data)
792{
793   ram[offset + 0] = data >> 8;
794   ram[offset + 1] = data >> 0;
795}
796
797
798/*-------------------------------------------------
799    fillbitmap_yuy16 - fill a YUY16 bitmap with a
800    given color pattern
801-------------------------------------------------*/
802
803INLINE void fillbitmap_yuy16(bitmap_t *bitmap, UINT8 yval, UINT8 cr, UINT8 cb)
804{
805   UINT16 color0 = (yval << 8) | cb;
806   UINT16 color1 = (yval << 8) | cr;
807   int x, y;
808
809   /* write 32 bits of color (2 pixels at a time) */
810   for (y = 0; y < bitmap->height; y++)
811   {
812      UINT16 *dest = (UINT16 *)bitmap->base + y * bitmap->rowpixels;
813      for (x = 0; x < bitmap->width / 2; x++)
814      {
815         *dest++ = color0;
816         *dest++ = color1;
817      }
818   }
819}
820
821
822
823/***************************************************************************
824    GENERIC IMPLEMENTATION
825***************************************************************************/
826
827/*-------------------------------------------------
828    laserdisc_vsync - call this once per field
829    on the VSYNC signal
830-------------------------------------------------*/
831
832void laserdisc_vsync(const device_config *device)
833{
834   laserdisc_state *ld = get_safe_token(device);
835   UINT8 origstate = ld->state;
836   UINT8 hittarget;
837   int backslash;
838
839   /* allow the backslash key to toggle the frame display */
840   backslash = input_code_pressed(KEYCODE_BACKSLASH);
841   if (!ld->lastbackslash && backslash)
842      ld->display ^= 1;
843   ld->lastbackslash = backslash;
844
845   /* remember the time */
846   ld->lastvsynctime = timer_get_time();
847
848   /* if we're holding, stay in this state until finished */
849   if (ld->holdfinished.seconds != 0 || ld->holdfinished.attoseconds != 0)
850   {
851      if (attotime_compare(ld->lastvsynctime, ld->holdfinished) < 0)
852         return;
853      ld->state = ld->postholdstate;
854      ld->curfracspeed = ld->postholdfracspeed;
855      ld->holdfinished.seconds = 0;
856      ld->holdfinished.attoseconds = 0;
857   }
858
859   /* wait for previous read and decode to finish */
860   process_track_data(device);
861
862   /* update our position for this field */
863   hittarget = update_position(ld);
864
865   /* switch off the state */
866   switch (ld->state)
867   {
868      /* parked: do nothing */
869      case LASERDISC_EJECTED:
870      case LASERDISC_EJECTING:
871      case LASERDISC_LOADED:
872      case LASERDISC_PARKED:
873         break;
874
875      /* playing: if we hit our target, indicate so; if we hit the beginning/end, stop */
876      case LASERDISC_STOPPED:
877      case LASERDISC_AUTOSTOPPED:
878      case LASERDISC_SEARCH_FINISHED:
879      case LASERDISC_PLAYING_FORWARD:
880      case LASERDISC_PLAYING_REVERSE:
881      case LASERDISC_PLAYING_SLOW_FORWARD:
882      case LASERDISC_PLAYING_SLOW_REVERSE:
883      case LASERDISC_PLAYING_FAST_FORWARD:
884      case LASERDISC_PLAYING_FAST_REVERSE:
885      case LASERDISC_STEPPING_FORWARD:
886      case LASERDISC_STEPPING_REVERSE:
887      case LASERDISC_SCANNING_FORWARD:
888      case LASERDISC_SCANNING_REVERSE:
889
890         /* autostop if we hit the target frame */
891         if (hittarget)
892            set_state(ld, LASERDISC_AUTOSTOPPED, STOP_SPEED, NULL_TARGET_FRAME);
893         break;
894
895      /* loading; keep searching until we hit the target, then go into the stopped state */
896      case LASERDISC_LOADING:
897      case LASERDISC_SPINUP:
898
899         /* if we hit the target, go into search finished state */
900         if (hittarget)
901            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
902         break;
903
904      /* searching; keep seeking until we hit the target */
905      case LASERDISC_SEARCHING_FRAME:
906
907         /* if we hit the target, go into search finished state */
908         if (hittarget)
909            set_state(ld, LASERDISC_SEARCH_FINISHED, STOP_SPEED, NULL_TARGET_FRAME);
910         break;
911   }
912
913   /* if the state changed, notify */
914   if (ld->state != origstate)
915   {
916      /* on a state change, implicity round to the nearest fraction */
917      ld->curfractrack = INT_TO_FRAC(FRAC_TO_INT(ld->curfractrack));
918      if (!(ld->fieldnum & 1))
919         ld->curfractrack += FRAC_ONE / 2;
920
921      /* notify the disc handler */
922      if (ld->statechanged != NULL)
923         (*ld->statechanged)(ld, origstate);
924   }
925
926   /* flush any audio before we read more */
927   if (ld->audiocustom != -1)
928   {
929      sound_token *token = custom_get_token(ld->audiocustom);
930      stream_update(token->stream);
931   }
932
933   /* start reading the track data for the next round */
934   ld->fieldnum++;
935   read_track_data(ld);
936}
937
938
939/*-------------------------------------------------
940    laserdisc_describe_state - return a text
941    string describing the current state
942-------------------------------------------------*/
943
944const char *laserdisc_describe_state(const device_config *device)
945{
946   static const struct
947   {
948      playstate state;
949      const char *string;
950   } state_strings[] =
951   {
952      { LASERDISC_EJECTED, "Ejected" },
953      { LASERDISC_EJECTING, "Ejecting" },
954      { LASERDISC_LOADED, "Loaded" },
955      { LASERDISC_LOADING, "Loading" },
956      { LASERDISC_SPINUP, "Spinning Up" },
957      { LASERDISC_PARKED, "Parked" },
958      { LASERDISC_SEARCHING_FRAME, "Searching Frame" },
959      { LASERDISC_SEARCH_FINISHED, "Search Finished" },
960      { LASERDISC_STOPPED, "Stopped" },
961      { LASERDISC_AUTOSTOPPED, "Autostopped" },
962      { LASERDISC_PLAYING_FORWARD, "Playing Forward" },
963      { LASERDISC_PLAYING_REVERSE, "Playing Reverse" },
964      { LASERDISC_PLAYING_SLOW_FORWARD, "Playing Slow Forward x" },
965      { LASERDISC_PLAYING_SLOW_REVERSE, "Playing Slow Reverse x" },
966      { LASERDISC_PLAYING_FAST_FORWARD, "Playing Fast Forward x" },
967      { LASERDISC_PLAYING_FAST_REVERSE, "Playing Fast Reverse x" },
968      { LASERDISC_STEPPING_FORWARD, "Stepping Forward" },
969      { LASERDISC_STEPPING_REVERSE, "Stepping Reverse" },
970      { LASERDISC_SCANNING_FORWARD, "Scanning Forward" },
971      { LASERDISC_SCANNING_REVERSE, "Scanning Reverse" }
972   };
973   laserdisc_state *ld = get_safe_token(device);
974   const char *description = "Unknown";
975   int i;
976
977   /* find the string */
978   for (i = 0; i < ARRAY_LENGTH(state_strings); i++)
979      if (state_strings[i].state == ld->state)
980         description = state_strings[i].string;
981
982   /* construct the string */
983   if (description[strlen(description) - 1] == 'x')
984      sprintf(ld->text, "%05d (%s%.1f)", FRAC_TO_INT(ld->curfractrack), description, (float)ld->curfracspeed / (float)INT_TO_FRAC(1));
985   else
986      sprintf(ld->text, "%05d (%s)", FRAC_TO_INT(ld->curfractrack), description);
987   return ld->text;
988}
989
990
991/*-------------------------------------------------
992    laserdisc_data_w - write data to the given
993    laserdisc player
994-------------------------------------------------*/
995
996void laserdisc_data_w(const device_config *device, UINT8 data)
997{
998   laserdisc_state *ld = get_safe_token(device);
999   UINT8 prev = ld->datain;
1000   ld->datain = data;
1001
1002   /* call through to the player-specific write handler */
1003   if (ld->writedata != NULL)
1004      (*ld->writedata)(ld, prev, data);
1005}
1006
1007
1008/*-------------------------------------------------
1009    laserdisc_line_w - control an input line
1010-------------------------------------------------*/
1011
1012void laserdisc_line_w(const device_config *device, UINT8 line, UINT8 newstate)
1013{
1014   laserdisc_state *ld = get_safe_token(device);
1015
1016   assert(line < LASERDISC_INPUT_LINES);
1017   assert(newstate == ASSERT_LINE || newstate == CLEAR_LINE || newstate == PULSE_LINE);
1018
1019   /* assert */
1020   if (newstate == ASSERT_LINE || newstate == PULSE_LINE)
1021   {
1022      if (ld->linein[line] != ASSERT_LINE)
1023      {
1024         /* call through to the player-specific line handler */
1025         if (ld->writeline[line] != NULL)
1026            (*ld->writeline[line])(ld, ASSERT_LINE);
1027      }
1028      ld->linein[line] = ASSERT_LINE;
1029   }
1030
1031   /* deassert */
1032   if (newstate == CLEAR_LINE || newstate == PULSE_LINE)
1033   {
1034      if (ld->linein[line] != CLEAR_LINE)
1035      {
1036         /* call through to the player-specific line handler */
1037         if (ld->writeline[line] != NULL)
1038            (*ld->writeline[line])(ld, CLEAR_LINE);
1039      }
1040      ld->linein[line] = CLEAR_LINE;
1041   }
1042}
1043
1044
1045/*-------------------------------------------------
1046    laserdisc_data_r - return the current
1047    data byte
1048-------------------------------------------------*/
1049
1050UINT8 laserdisc_data_r(const device_config *device)
1051{
1052   laserdisc_state *ld = get_safe_token(device);
1053   UINT8 result = ld->dataout;
1054
1055   /* call through to the player-specific data handler */
1056   if (ld->readdata != NULL)
1057      result = (*ld->readdata)(ld);
1058
1059   return result;
1060}
1061
1062
1063/*-------------------------------------------------
1064    laserdisc_line_r - return the current state
1065    of an output line
1066-------------------------------------------------*/
1067
1068UINT8 laserdisc_line_r(const device_config *device, UINT8 line)
1069{
1070   laserdisc_state *ld = get_safe_token(device);
1071   UINT8 result;
1072
1073   assert(line < LASERDISC_OUTPUT_LINES);
1074   result = ld->lineout[line];
1075
1076   /* call through to the player-specific data handler */
1077   if (ld->readline[line] != NULL)
1078      result = (*ld->readline[line])(ld);
1079
1080   return result;
1081}
1082
1083
1084/*-------------------------------------------------
1085    laserdisc_get_video - return the current
1086    video frame
1087-------------------------------------------------*/
1088
1089int laserdisc_get_video(const device_config *device, bitmap_t **bitmap)
1090{
1091   laserdisc_state *ld = get_safe_token(device);
1092   int frameindex;
1093
1094   /* determine the most recent live set of frames */
1095   frameindex = ld->videoindex;
1096   if (ld->videofields[frameindex] < 2)
1097      frameindex = (frameindex + ARRAY_LENGTH(ld->videofields) - 1) % ARRAY_LENGTH(ld->videofields);
1098
1099   /* if no video present, return the empty frame */
1100   if (!video_active(ld) || ld->videofields[frameindex] < 2)
1101   {
1102      *bitmap = ld->emptyframe;
1103      return FALSE;
1104   }
1105   else
1106   {
1107      *bitmap = ld->videovisframe[frameindex];
1108      return TRUE;
1109   }
1110}
1111
1112
1113/*-------------------------------------------------
1114    laserdisc_get_field_code - return raw field
1115    information read from the disc
1116-------------------------------------------------*/
1117
1118UINT32 laserdisc_get_field_code(const device_config *device, UINT8 code)
1119{
1120   laserdisc_state *ld = get_safe_token(device);
1121   int field = (ld->fieldnum & 1) ^ 1;
1122
1123   /* if no video present, return */
1124   if (!video_active(ld))
1125      return 0;
1126
1127   switch (code)
1128   {
1129      case LASERDISC_CODE_WHITE_FLAG:
1130         return ld->metadata[field].white;
1131
1132      case LASERDISC_CODE_LINE16:
1133         return ld->metadata[field].line16;
1134
1135      case LASERDISC_CODE_LINE17:
1136         return ld->metadata[field].line17;
1137
1138      case LASERDISC_CODE_LINE18:
1139         return ld->metadata[field].line18;
1140   }
1141
1142   return 0;
1143}
1144
1145
1146
1147/***************************************************************************
1148    GENERIC HELPER FUNCTIONS
1149***************************************************************************/
1150
1151/*-------------------------------------------------
1152    process_number - scan a list of bytecodes
1153    and treat them as single digits if we get
1154    a match
1155-------------------------------------------------*/
1156
1157static int process_number(laserdisc_state *ld, UINT8 byte, const UINT8 numbers[])
1158{
1159   int value;
1160
1161   /* look for a match in the list of number values; if we got one, append it to the parameter */
1162   for (value = 0; value < 10; value++)
1163      if (numbers[value] == byte)
1164      {
1165         ld->parameter = (ld->parameter == -1) ? value : (ld->parameter * 10 + value);
1166         return TRUE;
1167      }
1168
1169   /* no match; return FALSE */
1170   return FALSE;
1171}
1172
1173
1174/*-------------------------------------------------
1175    update_position - update the head position
1176    for this VSYNC
1177-------------------------------------------------*/
1178
1179static int update_position(laserdisc_state *ld)
1180{
1181   UINT32 tracknum = FRAC_TO_INT(ld->curfractrack);
1182   UINT32 fieldnum = ld->fieldnum & 1;
1183   INT32 speed = ld->curfracspeed;
1184   INT32 framedelta;
1185
1186   /* if video isn't active, we don't need to be careful about fields and frames */
1187   if (!video_active(ld))
1188   {
1189      int frame = frame_from_metadata(&ld->metadata[fieldnum]);
1190      int direction;
1191
1192      /* if we have no target, don't do anything */
1193      if (ld->targetframe == 0)
1194         return TRUE;
1195
1196      LOG_POSITION(("%d:track=%5d frame=%5d target=%5d ... ", fieldnum, tracknum, frame, ld->targetframe));
1197
1198      /* if we hit the first field of our frame, we're done */
1199      if (ld->last_frame == ld->targetframe && frame_from_metadata(&ld->metadata[fieldnum ^ 1]) == ld->targetframe && ld->metadata[fieldnum ^ 1].white)
1200      {
1201         ld->curfractrack = INT_TO_FRAC(tracknum);
1202         LOG_POSITION(("hit target\n"));
1203         return TRUE;
1204      }
1205
1206      /* if we didn't get any frame information this field, move onto the next */
1207      if (frame == -1)
1208      {
1209         /* if we're on the second field of a frame, the next frame is on the next track */
1210         /* but don't do it if we're seeking to frame 1, since that might be the very first frame */
1211         if (fieldnum == 1)
1212         {
1213            add_to_current_track(ld, ONE_TRACK);
1214            LOG_POSITION(("on 2nd field, going to next track\n"));
1215         }
1216         else
1217            LOG_POSITION(("no metadata; waiting for next field\n"));
1218         return FALSE;
1219      }
1220
1221      /* if we're in the lead-in or lead-out sections, advance more aggressively */
1222      if (frame == 0)
1223      {
1224         LOG_POSITION(("in lead-in, advancing by 1\n"));
1225         if (fieldnum == 1)
1226            add_to_current_track(ld, 1 * ONE_TRACK);
1227         return FALSE;
1228      }
1229      if (frame == 99999)
1230      {
1231         LOG_POSITION(("in lead-out, advancing by 10\n"));
1232         add_to_current_track(ld, -10 * ONE_TRACK);
1233         return FALSE;
1234      }
1235
1236      /* determine the frame delta and direction; for backwards seeks, aim to overshoot by 1 frame */
1237      if (ld->targetframe < frame && ld->targetframe != 1)
1238         framedelta = ld->targetframe - 1 - frame;
1239      else
1240         framedelta = ld->targetframe - frame;
1241      direction = (framedelta <= 0) ? -1 : 1;
1242
1243      /* if we're going backwards, go back at least 2 frames since we tend to move forward */
1244      if (framedelta == -1)
1245         framedelta = -2;
1246
1247      /* if we're only going forward one frame, only advance if we're on the second field */
1248      /* otherwise, we might overshoot */
1249      else if (framedelta == 1 && fieldnum == 0)
1250         framedelta = 0;
1251
1252      /* scale up to fractional bits */
1253      framedelta = INT_TO_FRAC(abs(framedelta));
1254
1255      /* determine the stepdelta */
1256      LOG_POSITION(("advancing by %08X\n", MIN(framedelta, speed / 2) * direction));
1257      add_to_current_track(ld, MIN(framedelta, speed / 2) * direction);
1258      return FALSE;
1259   }
1260
1261   /* only advance on the second field */
1262   if (fieldnum != 1)
1263      return FALSE;
1264
1265   /* if we're moving backwards, advance back until we hit track 1 or the target */
1266   if (speed < 0)
1267   {
1268      /* if we've hit the target, stop now */
1269      if (ld->targetframe != 0 && ld->last_frame <= ld->targetframe)
1270      {
1271         ld->curfractrack = INT_TO_FRAC(tracknum);
1272         return TRUE;
1273      }
1274
1275      /* otherwise, clamp our delta so we don't overshoot */
1276      else
1277      {
1278         framedelta = INT_TO_FRAC((ld->targetframe == 0) ? -1000 : (ld->targetframe - ld->last_frame));
1279         add_to_current_track(ld, MAX(framedelta, speed));
1280      }
1281   }
1282
1283   /* if we're moving forwards, advance forward until we hit the max track or the target */
1284   else if (speed > 0)
1285   {
1286      /* if we've hit the target, stop now */
1287      if (ld->targetframe != 0 && ld->last_frame >= ld->targetframe)
1288      {
1289         ld->curfractrack = INT_TO_FRAC(tracknum);
1290         return TRUE;
1291      }
1292
1293      /* otherwise, clamp our delta so we don't overshoot */
1294      else
1295      {
1296         framedelta = INT_TO_FRAC((ld->targetframe == 0) ? 1000 : (ld->targetframe - ld->last_frame));
1297         add_to_current_track(ld, MIN(framedelta, speed));
1298      }
1299   }
1300   return FALSE;
1301}
1302
1303
1304/*-------------------------------------------------
1305    read_track_data - read and process data for
1306    a particular video track
1307-------------------------------------------------*/
1308
1309static void read_track_data(laserdisc_state *ld)
1310{
1311   UINT32 tracknum = FRAC_TO_INT(ld->curfractrack);
1312   UINT32 fieldnum = ld->fieldnum & 1;
1313   UINT32 chdhunk = (tracknum - 1) * 2 + fieldnum;
1314   chd_error err;
1315
1316   /* if the previous field had the white flag, force the new field to pair with it */
1317   if (ld->metadata[fieldnum ^ 1].white)
1318      ld->videofields[ld->videoindex] = 1;
1319
1320   /* if we already have both fields on the current videoindex, advance */
1321   if (ld->videofields[ld->videoindex] >= 2)
1322   {
1323      ld->videoindex = (ld->videoindex + 1) % ARRAY_LENGTH(ld->videofields);
1324      ld->videofields[ld->videoindex] = 0;
1325   }
1326
1327   /* set the video target information */
1328   ld->videotarget = *ld->videoframe[ld->videoindex];
1329   ld->videotarget.base = BITMAP_ADDR16(&ld->videotarget, fieldnum, 0);
1330   ld->videotarget.height /= 2;
1331   ld->videotarget.rowpixels *= 2;
1332   ld->avconfig.video = &ld->videotarget;
1333
1334   /* set the audio target information */
1335   if (ld->audiobufin + ld->audiomaxsamples <= ld->audiobufsize)
1336   {
1337      /* if we can fit without wrapping, just read the data directly */
1338      ld->avconfig.audio[0] = &ld->audiobuffer[0][ld->audiobufin];
1339      ld->avconfig.audio[1] = &ld->audiobuffer[1][ld->audiobufin];
1340   }
1341   else
1342   {
1343      /* otherwise, read to the beginning of the buffer */
1344      ld->avconfig.audio[0] = &ld->audiobuffer[0][0];
1345      ld->avconfig.audio[1] = &ld->audiobuffer[1][0];
1346   }
1347
1348   /* override if we're not decoding */
1349   ld->avconfig.maxsamples = ld->audiomaxsamples;
1350   ld->avconfig.actsamples = &ld->audiocursamples;
1351   ld->audiocursamples = 0;
1352   if (!audio_channel_active(ld, 0))
1353      ld->avconfig.audio[0] = NULL;
1354   if (!audio_channel_active(ld, 1))
1355      ld->avconfig.audio[1] = NULL;
1356
1357   /* configure the codec and then read */
1358   if (ld->disc != NULL)
1359   {
1360      err = chd_codec_config(ld->disc, AV_CODEC_DECOMPRESS_CONFIG, &ld->avconfig);
1361      if (err == CHDERR_NONE)
1362      {
1363         err = chd_read_async(ld->disc, chdhunk, NULL);
1364         ld->readpending = TRUE;
1365      }
1366   }
1367}
1368
1369
1370/*-------------------------------------------------
1371    process_track_data - process data from a
1372    track after it has been read
1373-------------------------------------------------*/
1374
1375static void process_track_data(const device_config *device)
1376{
1377   laserdisc_state *ld = get_safe_token(device);
1378   UINT32 tracknum = FRAC_TO_INT(ld->curfractrack);
1379   UINT32 fieldnum = ld->fieldnum & 1;
1380   int frame, chapter;
1381   chd_error chderr;
1382
1383   /* wait for the async operation to complete */
1384   if (ld->disc != NULL && ld->readpending)
1385   {
1386      /* complete the async operation */
1387      chderr = chd_async_complete(ld->disc);
1388      if (chderr != CHDERR_NONE && chderr != CHDERR_NO_ASYNC_OPERATION)
1389         ld->avconfig.video = NULL;
1390   }
1391   ld->readpending = FALSE;
1392
1393   /* parse the metadata */
1394   if (ld->disc != NULL && ld->avconfig.video != NULL)
1395      vbi_parse_all((const UINT16 *)ld->avconfig.video->base, ld->avconfig.video->rowpixels, ld->avconfig.video->width, 8, &ld->metadata[fieldnum]);
1396   else
1397      fake_metadata(tracknum, fieldnum, &ld->metadata[fieldnum]);
1398//  printf("Track %5d: Metadata = %d %08X %08X %08X %08X\n", tracknum, ld->metadata[fieldnum].white, ld->metadata[fieldnum].line16, ld->metadata[fieldnum].line17, ld->metadata[fieldnum].line18, ld->metadata[fieldnum].line1718);
1399
1400   /* update the last seen frame and chapter */
1401   frame = frame_from_metadata(&ld->metadata[fieldnum]);
1402   if (frame >= 1 && frame < 99999)
1403      ld->last_frame = frame;
1404   chapter = chapter_from_metadata(&ld->metadata[fieldnum]);
1405   if (chapter != -1)
1406      ld->last_chapter = chapter;
1407
1408   /* render the display if present */
1409   if (ld->display && ld->avconfig.video != NULL)
1410      render_display((UINT16 *)ld->avconfig.video->base, ld->avconfig.video->rowpixels, ld->avconfig.video->width, ld->last_frame);
1411
1412   /* update video field */
1413   if (ld->avconfig.video != NULL)
1414   {
1415      ld->videofields[ld->videoindex]++;
1416      ld->videoframenum[ld->videoindex] = ld->last_frame;
1417   }
1418
1419   /* pass the audio to the callback */
1420   if (ld->config.audio != NULL)
1421      (*ld->config.audio)(device, ld->samplerate, ld->audiocursamples, ld->avconfig.audio[0], ld->avconfig.audio[1]);
1422
1423   /* shift audio data if we read it into the beginning of the buffer */
1424   if (ld->audiocursamples != 0 && ld->audiobufin != 0)
1425   {
1426      int chnum;
1427
1428      /* iterate over channels */
1429      for (chnum = 0; chnum < 2; chnum++)
1430         if (ld->avconfig.audio[chnum] == &ld->audiobuffer[chnum][0])
1431         {
1432            int samplesleft;
1433
1434            /* move data to the end */
1435            samplesleft = ld->audiobufsize - ld->audiobufin;
1436            samplesleft = MIN(samplesleft, ld->audiocursamples);
1437            memmove(&ld->audiobuffer[chnum][ld->audiobufin], &ld->audiobuffer[chnum][0], samplesleft * 2);
1438
1439            /* shift data at the beginning */
1440            if (samplesleft < ld->audiocursamples)
1441               memmove(&ld->audiobuffer[chnum][0], &ld->audiobuffer[chnum][samplesleft], (ld->audiocursamples - samplesleft) * 2);
1442         }
1443   }
1444
1445   /* update the input buffer pointer */
1446   ld->audiobufin = (ld->audiobufin + ld->audiocursamples) % ld->audiobufsize;
1447}
1448
1449
1450/*-------------------------------------------------
1451    fake_metadata - fake metadata when there's
1452    no disc present
1453-------------------------------------------------*/
1454
1455static void fake_metadata(UINT32 track, UINT8 which, vbi_metadata *metadata)
1456{
1457   if (which == 0)
1458   {
1459      metadata->white = 1;
1460      metadata->line16 = 0;
1461      metadata->line17 = metadata->line18 = 0xf80000 |
1462            (((track / 10000) % 10) << 16) |
1463            (((track / 1000) % 10) << 12) |
1464            (((track / 100) % 10) << 8) |
1465            (((track / 10) % 10) << 4) |
1466            (((track / 1) % 10) << 0);
1467   }
1468   else
1469      memset(metadata, 0, sizeof(*metadata));
1470}
1471
1472
1473/*-------------------------------------------------
1474    render_display - draw the frame display
1475-------------------------------------------------*/
1476
1477static void render_display(UINT16 *videodata, UINT32 rowpixels, UINT32 width, int frame)
1478{
1479   const int xscale = 4, yscale = 2;
1480   char buffer[10];
1481   int x = width / 10;
1482   int y = 50;
1483   int ch;
1484   int delta;
1485
1486   /* do nothing if no data */
1487   if (videodata == NULL)
1488      return;
1489
1490   /* convert to a character string and render */
1491   sprintf(buffer, "%5d", frame);
1492
1493   /* iterate over 5 positions: (-1,-1), (-1,1), (1,-1), (1,1) and (0,0) */
1494   /* render all in black except the last one */
1495   for (delta = 0; delta < 5; delta++)
1496   {
1497      int color = (delta < 4) ? 0x0080 : 0xff80;
1498      int dx = (delta < 4) ? ((delta & 1) ? -1 : 1) : 0;
1499      int dy = (delta < 4) ? ((delta & 2) ? -1 : 1) : 0;
1500
1501      /* iterate over 5 characters */
1502      for (ch = 0; ch < 5; ch++)
1503         if (buffer[ch] >= '0' && buffer[ch] <= '9')
1504         {
1505            const UINT8 *fontdata = &numberfont[buffer[ch] - '0'][0];
1506            int cy, cx;
1507
1508            /* iterate over the rows of the character */
1509            for (cy = 0; cy < 8; cy++)
1510            {
1511               UINT8 bits = *fontdata++;
1512
1513               /* and over the columns */
1514               for (cx = 0; cx < 8; cx++)
1515                  if (bits & (0x80 >> cx))
1516                  {
1517                     int ix, iy;
1518
1519                     /* fill in an xscale x yscale pixel */
1520                     for (iy = 0; iy < yscale; iy++)
1521                        for (ix = 0; ix < xscale; ix++)
1522                           videodata[(y + cy * yscale + iy + dy) * rowpixels + (x + (ch * 9 + cx) * xscale + ix + dx)] = color;
1523                  }
1524            }
1525         }
1526   }
1527}
1528
1529
1530/*-------------------------------------------------
1531    custom_start - custom audio start
1532    for laserdiscs
1533-------------------------------------------------*/
1534
1535static void *custom_start(int clock, const custom_sound_interface *config)
1536{
1537   sound_token *token = auto_malloc(sizeof(*token));
1538   token->stream = stream_create(0, 2, 48000, token, custom_stream_callback);
1539   token->ld = NULL;
1540   return token;
1541}
1542
1543
1544/*-------------------------------------------------
1545    custom_stream_callback - audio streamer
1546    for laserdiscs
1547-------------------------------------------------*/
1548
1549static void custom_stream_callback(void *param, stream_sample_t **inputs, stream_sample_t **outputs, int samples)
1550{
1551   sound_token *token = param;
1552   laserdisc_state *ld = token->ld;
1553   stream_sample_t *dst0 = outputs[0];
1554   stream_sample_t *dst1 = outputs[1];
1555   int samples_avail = 0;
1556
1557   /* see if we have enough samples to fill the buffer; if not, drop out */
1558   if (ld != NULL)
1559   {
1560      samples_avail = ld->audiobufin - ld->audiobufout;
1561      if (samples_avail < 0)
1562         samples_avail += ld->audiobufsize;
1563   }
1564
1565   /* if no attached ld, just clear the buffers */
1566   if (samples_avail < samples)
1567   {
1568      memset(dst0, 0, samples * sizeof(dst0[0]));
1569      memset(dst1, 0, samples * sizeof(dst1[0]));
1570   }
1571
1572   /* otherwise, stream from our buffer */
1573   else
1574   {
1575      INT16 *buffer0 = ld->audiobuffer[0];
1576      INT16 *buffer1 = ld->audiobuffer[1];
1577      int sampout = ld->audiobufout;
1578
1579      /* copy samples, clearing behind us as we go */
1580      while (sampout != ld->audiobufin && samples-- > 0)
1581      {
1582         *dst0++ = buffer0[sampout];
1583         *dst1++ = buffer1[sampout];
1584         buffer0[sampout] = 0;
1585         buffer1[sampout] = 0;
1586         sampout++;
1587         if (sampout >= ld->audiobufsize)
1588            sampout = 0;
1589      }
1590      ld->audiobufout = sampout;
1591
1592      /* clear out the rest of the buffer */
1593      if (samples > 0)
1594      {
1595         int sampout = (ld->audiobufout == 0) ? ld->audiobufsize - 1 : ld->audiobufout - 1;
1596         stream_sample_t fill0 = buffer0[sampout];
1597         stream_sample_t fill1 = buffer1[sampout];
1598
1599         while (samples-- > 0)
1600         {
1601            *dst0++ = fill0;
1602            *dst1++ = fill1;
1603         }
1604      }
1605   }
1606}
1607
1608
1609
1610/***************************************************************************
1611    CONFIG SETTINGS ACCESS
1612***************************************************************************/
1613
1614/*-------------------------------------------------
1615    configuration_load - read and apply data from
1616    the configuration file
1617-------------------------------------------------*/
1618
1619static void configuration_load(running_machine *machine, int config_type, xml_data_node *parentnode)
1620{
1621   xml_data_node *overnode;
1622   xml_data_node *ldnode;
1623
1624   /* we only care about game files */
1625   if (config_type != CONFIG_TYPE_GAME)
1626      return;
1627
1628   /* might not have any data */
1629   if (parentnode == NULL)
1630      return;
1631
1632   /* iterate over overlay nodes */
1633   for (ldnode = xml_get_sibling(parentnode->child, "device"); ldnode != NULL; ldnode = xml_get_sibling(ldnode->next, "device"))
1634   {
1635      const char *devtag = xml_get_attribute_string(ldnode, "tag", "");
1636      const device_config *device = device_list_find_by_tag(machine->config->devicelist, LASERDISC, devtag);
1637      if (device != NULL)
1638      {
1639         laserdisc_state *ld = get_safe_token(device);
1640
1641         /* handle the overlay node */
1642         overnode = xml_get_sibling(ldnode->child, "overlay");
1643         if (overnode != NULL)
1644         {
1645            /* fetch positioning controls */
1646            ld->config.overposx = xml_get_attribute_float(overnode, "hoffset", ld->config.overposx);
1647            ld->config.overscalex = xml_get_attribute_float(overnode, "hstretch", ld->config.overscalex);
1648            ld->config.overposy = xml_get_attribute_float(overnode, "voffset", ld->config.overposy);
1649            ld->config.overscaley = xml_get_attribute_float(overnode, "vstretch", ld->config.overscaley);
1650         }
1651      }
1652   }
1653}
1654
1655
1656/*-------------------------------------------------
1657    configuration_save - save data to the
1658    configuration file
1659-------------------------------------------------*/
1660
1661static void configuration_save(running_machine *machine, int config_type, xml_data_node *parentnode)
1662{
1663   const device_config *device;
1664
1665   /* we only care about game files */
1666   if (config_type != CONFIG_TYPE_GAME)
1667      return;
1668
1669   /* iterate over disc devices */
1670   for (device = device_list_first(machine->config->devicelist, LASERDISC); device != NULL; device = device_list_next(device, LASERDISC))
1671   {
1672      laserdisc_config *origconfig = device->inline_config;
1673      laserdisc_state *ld = get_safe_token(device);
1674      xml_data_node *overnode;
1675      xml_data_node *ldnode;
1676
1677      /* create a node */
1678      ldnode = xml_add_child(parentnode, "device", NULL);
1679      if (ldnode != NULL)
1680      {
1681         int changed = FALSE;
1682
1683         /* output the basics */
1684         xml_set_attribute(ldnode, "tag", device->tag);
1685
1686         /* add an overlay node */
1687         overnode = xml_add_child(ldnode, "overlay", NULL);
1688         if (overnode != NULL)
1689         {
1690            /* output the positioning controls */
1691            if (ld->config.overposx != origconfig->overposx)
1692            {
1693               xml_set_attribute_float(overnode, "hoffset", ld->config.overposx);
1694               changed = TRUE;
1695            }
1696
1697            if (ld->config.overscalex != origconfig->overscalex)
1698            {
1699               xml_set_attribute_float(overnode, "hstretch", ld->config.overscalex);
1700               changed = TRUE;
1701            }
1702
1703            if (ld->config.overposy != origconfig->overposy)
1704            {
1705               xml_set_attribute_float(overnode, "voffset", ld->config.overposy);
1706               changed = TRUE;
1707            }
1708
1709            if (ld->config.overscaley != origconfig->overscaley)
1710            {
1711               xml_set_attribute_float(overnode, "vstretch", ld->config.overscaley);
1712               changed = TRUE;
1713            }
1714         }
1715
1716         /* if nothing changed, kill the node */
1717         if (!changed)
1718            xml_delete_node(ldnode);
1719      }
1720   }
1721}
1722
1723
1724
1725/***************************************************************************
1726    VIDEO INTERFACE
1727***************************************************************************/
1728
1729/*-------------------------------------------------
1730    laserdisc_video_enable - enable/disable the
1731    video
1732-------------------------------------------------*/
1733
1734void laserdisc_video_enable(const device_config *device, int enable)
1735{
1736   laserdisc_state *ld = get_safe_token(device);
1737   ld->videoenable = enable;
1738}
1739
1740
1741/*-------------------------------------------------
1742    laserdisc_video_enable - enable/disable the
1743    video
1744-------------------------------------------------*/
1745
1746void laserdisc_overlay_enable(const device_config *device, int enable)
1747{
1748   laserdisc_state *ld = get_safe_token(device);
1749   ld->overenable = enable;
1750}
1751
1752
1753/*-------------------------------------------------
1754    video update callback
1755-------------------------------------------------*/
1756
1757VIDEO_UPDATE( laserdisc )
1758{
1759   const device_config *laserdisc = device_list_first(screen->machine->config->devicelist, LASERDISC);
1760   if (laserdisc != NULL)
1761   {
1762      laserdisc_state *ld = laserdisc->token;
1763      bitmap_t *overbitmap = ld->overbitmap[ld->overindex];
1764      bitmap_t *vidbitmap = NULL;
1765
1766      /* handle the overlay if present */
1767      if (overbitmap != NULL)
1768      {
1769         rectangle clip = *cliprect;
1770
1771         /* scale the cliprect to the overlay size */
1772         clip.min_x = 0;
1773         clip.max_x = ld->config.overwidth - 1;
1774         clip.min_y = cliprect->min_y * overbitmap->height / bitmap->height;
1775         clip.max_y = (cliprect->max_y + 1) * overbitmap->height / bitmap->height - 1;
1776
1777         /* call the callback */
1778         if (ld->config.overupdate != NULL)
1779            (*ld->config.overupdate)(screen, overbitmap, &clip);
1780      }
1781
1782      /* if this is the last update, do the rendering */
1783      if (cliprect->max_y == video_screen_get_visible_area(screen)->max_y)
1784      {
1785         float x0, y0, x1, y1;
1786
1787         /* update the texture with the overlay contents */
1788         if (overbitmap != NULL)
1789         {
1790            if (overbitmap->format == BITMAP_FORMAT_INDEXED16)
1791               render_texture_set_bitmap(ld->overtex, overbitmap, &ld->config.overclip, 0, TEXFORMAT_PALETTEA16);
1792            else if (overbitmap->format == BITMAP_FORMAT_RGB32)
1793               render_texture_set_bitmap(ld->overtex, overbitmap, &ld->config.overclip, 0, TEXFORMAT_ARGB32);
1794         }
1795
1796         /* get the laserdisc video */
1797         laserdisc_get_video(laserdisc, &vidbitmap);
1798         if (vidbitmap != NULL)
1799            render_texture_set_bitmap(ld->videotex, vidbitmap, NULL, 0, TEXFORMAT_YUY16);
1800
1801         /* reset the screen contents */
1802         render_container_empty(render_container_get_screen(screen));
1803
1804         /* add the video texture */
1805         if (ld->videoenable)
1806            render_screen_add_quad(screen, 0.0f, 0.0f, 1.0f, 1.0f, MAKE_ARGB(0xff,0xff,0xff,0xff), ld->videotex, PRIMFLAG_BLENDMODE(BLENDMODE_NONE) | PRIMFLAG_SCREENTEX(1));
1807
1808         /* add the overlay */
1809         if (ld->overenable && overbitmap != NULL)
1810         {
1811            x0 = 0.5f - 0.5f * ld->config.overscalex + ld->config.overposx;
1812            y0 = 0.5f - 0.5f * ld->config.overscaley + ld->config.overposy;
1813            x1 = x0 + ld->config.overscalex;
1814            y1 = y0 + ld->config.overscaley;
1815            render_screen_add_quad(screen, x0, y0, x1, y1, MAKE_ARGB(0xff,0xff,0xff,0xff), ld->overtex, PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA) | PRIMFLAG_SCREENTEX(1));
1816         }
1817
1818         /* swap to the next bitmap */
1819         ld->overindex = (ld->overindex + 1) % ARRAY_LENGTH(ld->overbitmap);
1820      }
1821   }
1822
1823   return 0;
1824}
1825
1826
1827
1828/***************************************************************************
1829    CONFIGURATION
1830***************************************************************************/
1831
1832/*-------------------------------------------------
1833    laserdisc_get_config - return a copy of the
1834    current live configuration settings
1835-------------------------------------------------*/
1836
1837void laserdisc_get_config(const device_config *device, laserdisc_config *config)
1838{
1839   laserdisc_state *ld = get_safe_token(device);
1840   *config = ld->config;
1841}
1842
1843
1844/*-------------------------------------------------
1845    laserdisc_get_config - change the current live
1846    configuration settings
1847-------------------------------------------------*/
1848
1849void laserdisc_set_config(const device_config *device, const laserdisc_config *config)
1850{
1851   laserdisc_state *ld = get_safe_token(device);
1852   ld->config = *config;
1853}
1854
1855
1856
1857/***************************************************************************
1858    DEVICE INTERFACE
1859***************************************************************************/
1860
1861/*-------------------------------------------------
1862    device start callback
1863-------------------------------------------------*/
1864
1865static DEVICE_START( laserdisc )
1866{
1867   int fps = 30, fpsfrac = 0, width = 720, height = 240, interlaced = 1, channels = 2, rate = 44100;
1868   const laserdisc_config *config = device->inline_config;
1869   laserdisc_state *ld = get_safe_token(device);
1870   UINT32 fps_times_1million;
1871   char metadata[256];
1872   int sndnum, index;
1873   chd_error err;
1874
1875   /* copy config data to the live state */
1876   ld->config = *config;
1877   if (ld->config.overclip.max_x == ld->config.overclip.min_x || ld->config.overclip.max_y == ld->config.overclip.min_y)
1878   {
1879      ld->config.overclip.min_x = ld->config.overclip.min_y = 0;
1880      ld->config.overclip.max_x = ld->config.overwidth - 1;
1881      ld->config.overclip.max_y = ld->config.overheight - 1;
1882   }
1883   if (ld->config.overscalex == 0)
1884      ld->config.overscalex = 1.0f;
1885   if (ld->config.overscaley == 0)
1886      ld->config.overscaley = 1.0f;
1887
1888   /* find the disc */
1889   ld->disc = get_disk_handle(device->tag);
1890   ld->audiocustom = 0;
1891   for (sndnum = 0; sndnum < MAX_SOUND; sndnum++)
1892   {
1893      if (device->machine->config->sound[sndnum].tag != NULL && strcmp(device->machine->config->sound[sndnum].tag, device->tag) == 0)
1894         break;
1895      if (device->machine->config->sound[sndnum].type == SOUND_CUSTOM)
1896         ld->audiocustom++;
1897   }
1898   if (sndnum == MAX_SOUND)
1899      ld->audiocustom = -1;
1900
1901   /* get the disc metadata and extract the ld */
1902   if (ld->disc != NULL)
1903   {
1904      /* require the A/V codec */
1905      if (chd_get_header(ld->disc)->compression != CHDCOMPRESSION_AV)
1906         fatalerror("Laserdisc video must be compressed with the A/V codec!");
1907
1908      /* read and extract the metadata */
1909      err = chd_get_metadata(ld->disc, AV_METADATA_TAG, 0, metadata, sizeof(metadata), NULL, NULL);
1910      if (err != CHDERR_NONE)
1911         fatalerror("Non-A/V CHD file specified");
1912      if (sscanf(metadata, AV_METADATA_FORMAT, &fps, &fpsfrac, &width, &height, &interlaced, &channels, &rate) != 7)
1913         fatalerror("Invalid metadata in CHD file");
1914
1915      /* require interlaced video */
1916      if (!interlaced)
1917         fatalerror("Laserdisc video must be interlaced!");
1918
1919      /* determine the maximum track and allocate a frame buffer */
1920      ld->maxfractrack = INT_TO_FRAC(chd_get_header(ld->disc)->totalhunks / (interlaced + 1));
1921   }
1922   else
1923      ld->maxfractrack = INT_TO_FRAC(54000);
1924
1925   /* allocate video frames */
1926   for (index = 0; index < ARRAY_LENGTH(ld->videofields); index++)
1927   {
1928      ld->videoframe[index] = auto_bitmap_alloc(width, height * 2, BITMAP_FORMAT_YUY16);
1929      ld->videovisframe[index] = auto_malloc(sizeof(*ld->videovisframe[index]));
1930      *ld->videovisframe[index] = *ld->videoframe[index];
1931      ld->videovisframe[index]->base = BITMAP_ADDR16(ld->videovisframe[index], 44, ld->videoframe[index]->width * 8 / 720);
1932      ld->videovisframe[index]->height -= 44;
1933      ld->videovisframe[index]->width -= 2 * ld->videoframe[index]->width * 8 / 720;
1934      fillbitmap_yuy16(ld->videoframe[index], 40, 109, 240);
1935   }
1936   ld->emptyframe = auto_bitmap_alloc(width, height * 2, BITMAP_FORMAT_YUY16);
1937   fillbitmap_yuy16(ld->emptyframe, 0, 128, 128);
1938
1939   /* allocate audio buffers */
1940   fps_times_1million = fps * 1000000 + fpsfrac;
1941   ld->audiomaxsamples = ((UINT64)rate * 1000000 + fps_times_1million - 1) / fps_times_1million;
1942   ld->audiobufsize = ld->audiomaxsamples * 4;
1943   ld->audiobuffer[0] = auto_malloc(ld->audiobufsize * sizeof(ld->audiobuffer[0][0]));
1944   ld->audiobuffer[1] = auto_malloc(ld->audiobufsize * sizeof(ld->audiobuffer[1][0]));
1945   ld->samplerate = rate;
1946
1947   /* allocate texture for rendering */
1948   ld->videoenable = TRUE;
1949   ld->videotex = render_texture_alloc(NULL, NULL);
1950   if (ld->videotex == NULL)
1951      fatalerror("Out of memory allocating video texture");
1952
1953   /* allocate overlay */
1954   if (ld->config.overwidth > 0 && ld->config.overheight > 0 && ld->config.overupdate != NULL)
1955   {
1956      ld->overenable = TRUE;
1957      ld->overbitmap[0] = auto_bitmap_alloc(ld->config.overwidth, ld->config.overheight, ld->config.overformat);
1958      ld->overbitmap[1] = auto_bitmap_alloc(ld->config.overwidth, ld->config.overheight, ld->config.overformat);
1959      ld->overtex = render_texture_alloc(NULL, NULL);
1960      if (ld->overtex == NULL)
1961         fatalerror("Out of memory allocating overlay texture");
1962   }
1963
1964   /* register callbacks */
1965   config_register(device->machine, "laserdisc", configuration_load, configuration_save);
1966
1967   return DEVICE_START_OK;
1968}
1969
1970
1971/*-------------------------------------------------
1972    device exit callback
1973-------------------------------------------------*/
1974
1975static DEVICE_STOP( laserdisc )
1976{
1977   laserdisc_state *ld = get_safe_token(device);
1978
1979   /* make sure all async operations have completed */
1980   if (ld->disc != NULL)
1981      chd_async_complete(ld->disc);
1982
1983   /* free any textures */
1984   if (ld->videotex != NULL)
1985      render_texture_free(ld->videotex);
1986   if (ld->overtex != NULL)
1987      render_texture_free(ld->overtex);
1988}
1989
1990
1991/*-------------------------------------------------
1992    device reset callback
1993-------------------------------------------------*/
1994
1995static DEVICE_RESET( laserdisc )
1996{
1997   laserdisc_state *ld = get_safe_token(device);
1998   int i;
1999
2000   /* attempt to wire up the audio */
2001   if (ld->audiocustom != -1)
2002   {
2003      sound_token *token = custom_get_token(ld->audiocustom);
2004      token->ld = ld;
2005      stream_set_sample_rate(token->stream, ld->samplerate);
2006   }
2007
2008   /* set up the general ld */
2009   ld->video = VIDEO_ENABLE;
2010   ld->audio = AUDIO_CH1_ENABLE | AUDIO_CH2_ENABLE;
2011   ld->display = DISPLAY_ENABLE;
2012
2013   /* seek to frame 1 to start with */
2014   set_state(ld, LASERDISC_LOADING, GENERIC_RESET_SPEED, 1);
2015
2016   /* reset the I/O lines */
2017   for (i = 0; i < LASERDISC_INPUT_LINES; i++)
2018      ld->linein[i] = CLEAR_LINE;
2019   for (i = 0; i < LASERDISC_OUTPUT_LINES; i++)
2020      ld->lineout[i] = CLEAR_LINE;
2021
2022   /* reset callbacks */
2023   ld->writedata = NULL;
2024   memset(ld->writeline, 0, sizeof(ld->writeline));
2025   ld->readdata = NULL;
2026   memset(ld->readline, 0, sizeof(ld->readline));
2027   ld->statechanged = NULL;
2028
2029   /* each player can init */
2030   switch (ld->config.type)
2031   {
2032      case LASERDISC_TYPE_PIONEER_PR7820:
2033         pr7820_init(ld);
2034         break;
2035
2036      case LASERDISC_TYPE_PIONEER_PR8210:
2037         pr8210_init(ld);
2038         break;
2039
2040      case LASERDISC_TYPE_SIMUTREK_SPECIAL:
2041         simutrek_init(ld);
2042         break;
2043
2044      case LASERDISC_TYPE_PIONEER_LDV1000:
2045         ldv1000_init(ld);
2046         break;
2047
2048      case LASERDISC_TYPE_SONY_LDP1450:
2049         ldp1450_init(ld);
2050         break;
2051
2052      case LASERDISC_TYPE_PHILLIPS_22VP932:
2053         vp932_init(ld);
2054         break;
2055
2056      default:
2057         fatalerror("Invalid laserdisc player type!");
2058         break;
2059   }
2060
2061   /* default to track 1 */
2062   reset_tracknum(ld);
2063}
2064
2065
2066/*-------------------------------------------------
2067    device set info callback
2068-------------------------------------------------*/
2069
2070static DEVICE_SET_INFO( laserdisc )
2071{
2072   laserdisc_state *ld = get_safe_token(device);
2073   switch (state)
2074   {
2075      /* --- the following bits of info are set as 64-bit signed integers --- */
2076      case LDINFO_INT_TYPE:
2077         if (ld != NULL && ld->config.type != info->i)
2078         {
2079            ld->config.type = info->i;
2080            device_reset(device);
2081         }
2082         break;
2083   }
2084}
2085
2086
2087/*-------------------------------------------------
2088    device get info callback
2089-------------------------------------------------*/
2090
2091DEVICE_GET_INFO( laserdisc )
2092{
2093   const laserdisc_config *config = NULL;
2094
2095   if (device != NULL)
2096   {
2097      laserdisc_state *ld = device->token;
2098      config = (ld == NULL) ? device->inline_config : &ld->config;
2099   }
2100
2101   switch (state)
2102   {
2103      /* --- the following bits of info are returned as 64-bit signed integers --- */
2104      case DEVINFO_INT_TOKEN_BYTES:         info->i = sizeof(laserdisc_state);               break;
2105      case DEVINFO_INT_INLINE_CONFIG_BYTES:   info->i = sizeof(laserdisc_config);               break;
2106      case DEVINFO_INT_CLASS:               info->i = DEVICE_CLASS_VIDEO;                  break;
2107      case LDINFO_INT_TYPE:               info->i = config->type;                        break;
2108
2109      /* --- the following bits of info are returned as pointers to data or functions --- */
2110      case DEVINFO_FCT_SET_INFO:            info->set_info = DEVICE_SET_INFO_NAME(laserdisc);    break;
2111      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(laserdisc);       break;
2112      case DEVINFO_FCT_STOP:               info->stop = DEVICE_STOP_NAME(laserdisc);          break;
2113      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(laserdisc);         break;
2114
2115      /* --- the following bits of info are returned as NULL-terminated strings --- */
2116      case DEVINFO_STR_NAME:
2117         switch (config->type)
2118         {
2119            default:
2120            case LASERDISC_TYPE_PIONEER_PR7820:      info->s = "Pioneer PR-7820";      break;
2121            case LASERDISC_TYPE_PIONEER_PR8210:      info->s = "Pioneer PR-8210";      break;
2122            case LASERDISC_TYPE_SIMUTREK_SPECIAL:   info->s = "Simutrek Modified LDP";   break;
2123            case LASERDISC_TYPE_PIONEER_LDV1000:   info->s = "Pioneer LD-V1000";      break;
2124            case LASERDISC_TYPE_PHILLIPS_22VP932:   info->s = "Philips 22VP932";      break;
2125            case LASERDISC_TYPE_SONY_LDP1450:      info->s = "Sony LDP-1450";         break;
2126         }
2127         break;
2128      case DEVINFO_STR_FAMILY:            info->s = "Laserdisc Player";         break;
2129      case DEVINFO_STR_VERSION:            info->s = "1.0";                  break;
2130      case DEVINFO_STR_SOURCE_FILE:         info->s = __FILE__;                  break;
2131      case DEVINFO_STR_CREDITS:            info->s = "Copyright Nicola Salmoria and the MAME Team"; break;
2132   }
2133}
2134
2135
2136
2137/***************************************************************************
2138    PIONEER PR-7820 IMPLEMENTATION
2139***************************************************************************/
2140
2141/*-------------------------------------------------
2142    pr7820_init - Pioneer PR-7820-specific
2143    initialization
2144-------------------------------------------------*/
2145
2146static void pr7820_init(laserdisc_state *ld)
2147{
2148   pr7820_info *pr7820 = &ld->u.pr7820;
2149
2150   /* set up the write callbacks */
2151   ld->writeline[LASERDISC_LINE_ENTER] = pr7820_enter_w;
2152
2153   /* set up the read callbacks */
2154   ld->readdata = pr7820_status_r;
2155   ld->readline[LASERDISC_LINE_READY] = pr7820_ready_r;
2156
2157   /* do a soft reset */
2158   pr7820->configspeed = PLAY_SPEED / 2;
2159   pr7820_soft_reset(ld);
2160}
2161
2162
2163/*-------------------------------------------------
2164    pr7820_soft_reset - Pioneer PR-7820-specific
2165    soft reset
2166-------------------------------------------------*/
2167
2168static void pr7820_soft_reset(laserdisc_state *ld)
2169{
2170   pr7820_info *pr7820 = &ld->u.pr7820;
2171
2172   ld->audio = AUDIO_CH1_ENABLE  | AUDIO_CH2_ENABLE;
2173   ld->display = 0;
2174   pr7820->mode = PR7820_MODE_MANUAL;
2175   pr7820->activereg = 0;
2176   write_16bits_to_ram_be(pr7820->ram, 0, 1);
2177}
2178
2179
2180/*-------------------------------------------------
2181    pr7820_enter_w - write callback when the
2182    ENTER state is asserted
2183-------------------------------------------------*/
2184
2185static void pr7820_enter_w(laserdisc_state *ld, UINT8 newstate)
2186{
2187   static const UINT8 numbers[10] = { 0x3f, 0x0f, 0x8f, 0x4f, 0x2f, 0xaf, 0x6f, 0x1f, 0x9f, 0x5f };
2188   pr7820_info *pr7820 = &ld->u.pr7820;
2189   UINT8 data = (pr7820->mode == PR7820_MODE_AUTOMATIC) ? pr7820->ram[pr7820->curpc++ % 1024] : ld->datain;
2190
2191   /* we only care about assertions */
2192   if (newstate != ASSERT_LINE)
2193      return;
2194
2195   /* if we're in program mode, just write data */
2196   if (pr7820->mode == PR7820_MODE_PROGRAM && data != 0xef)
2197   {
2198      pr7820->ram[ld->parameter++ % 1024] = data;
2199      return;
2200   }
2201
2202   /* look for and process numbers */
2203   if (process_number(ld, data, numbers))
2204      return;
2205
2206   /* handle commands */
2207   switch (data)
2208   {
2209      case 0x7f:  CMDPRINTF(("pr7820: %d Recall\n", ld->parameter));
2210         /* set the active register */
2211         pr7820->activereg = ld->parameter;
2212         break;
2213
2214      case 0xa0:
2215      case 0xa1:
2216      case 0xa2:
2217      case 0xa3:   CMDPRINTF(("pr7820: Direct audio control %d\n", data & 0x03));
2218         /* control both channels directly */
2219         ld->audio = 0;
2220         if (data & 0x01)
2221            ld->audio |= AUDIO_CH1_ENABLE;
2222         if (data & 0x02)
2223            ld->audio |= AUDIO_CH2_ENABLE;
2224         break;
2225
2226      case 0xbf:   CMDPRINTF(("pr7820: %d Halt\n", ld->parameter));
2227         /* stop automatic mode */
2228         pr7820->mode = PR7820_MODE_MANUAL;
2229         break;
2230
2231      case 0xcc:   CMDPRINTF(("pr7820: Load\n"));
2232         /* load program from disc -- not implemented */
2233         break;
2234
2235      case 0xcf:   CMDPRINTF(("pr7820: %d Branch\n", ld->parameter));
2236         /* branch to a new PC */
2237         if (pr7820->mode == PR7820_MODE_AUTOMATIC)
2238            pr7820->curpc = (ld->parameter == -1) ? 0 : ld->parameter;
2239         break;
2240
2241      case 0xdf:   CMDPRINTF(("pr7820: %d Write program\n", ld->parameter));
2242         /* enter program mode */
2243         pr7820->mode = PR7820_MODE_PROGRAM;
2244         break;
2245
2246      case 0xe1:  CMDPRINTF(("pr7820: Soft Reset\n"));
2247         /* soft reset */
2248         pr7820_soft_reset(ld);
2249         break;
2250
2251      case 0xe3:  CMDPRINTF(("pr7820: Display off\n"));
2252         /* turn off frame display */
2253         ld->display = 0x00;
2254         break;
2255
2256      case 0xe4:  CMDPRINTF(("pr7820: Display on\n"));
2257         /* turn on frame display */
2258         ld->display = 0x01;
2259         break;
2260
2261      case 0xe5:  CMDPRINTF(("pr7820: Audio 2 off\n"));
2262         /* turn off audio channel 2 */
2263         ld->audio &= ~AUDIO_CH2_ENABLE;
2264         break;
2265
2266      case 0xe6:  CMDPRINTF(("pr7820: Audio 2 on\n"));
2267         /* turn on audio channel 2 */
2268         ld->audio |= AUDIO_CH2_ENABLE;
2269         break;
2270
2271      case 0xe7:  CMDPRINTF(("pr7820: Audio 1 off\n"));
2272         /* turn off audio channel 1 */
2273         ld->audio &= ~AUDIO_CH1_ENABLE;
2274         break;
2275
2276      case 0xe8:  CMDPRINTF(("pr7820: Audio 1 on\n"));
2277         /* turn on audio channel 1 */
2278         ld->audio |= AUDIO_CH1_ENABLE;
2279         break;
2280
2281      case 0xe9:   CMDPRINTF(("pr7820: %d Dump RAM\n", ld->parameter));
2282         /* not implemented */
2283         break;
2284
2285      case 0xea:   CMDPRINTF(("pr7820: %d Dump frame\n", ld->parameter));
2286         /* not implemented */
2287         break;
2288
2289      case 0xeb:   CMDPRINTF(("pr7820: %d Dump player status\n", ld->parameter));
2290         /* not implemented */
2291         break;
2292
2293      case 0xef:   CMDPRINTF(("pr7820: %d End program\n", ld->parameter));
2294         /* exit programming mode */
2295         pr7820->mode = PR7820_MODE_MANUAL;
2296         break;
2297
2298      case 0xf0:   CMDPRINTF(("pr7820: %d Decrement reg\n", ld->parameter));
2299         /* decrement register; if we hit 0, skip past the next branch statement */
2300         if (pr7820->mode == PR7820_MODE_AUTOMATIC)
2301         {
2302            UINT16 tempreg = read_16bits_from_ram_be(pr7820->ram, (ld->parameter * 2) % 1024);
2303            tempreg = (tempreg == 0) ? 0 : tempreg - 1;
2304            write_16bits_to_ram_be(pr7820->ram, (ld->parameter * 2) % 1024, tempreg);
2305            if (tempreg == 0)
2306               while (pr7820->ram[pr7820->curpc++ % 1024] != 0xcf) ;
2307         }
2308         break;
2309
2310      case 0xf1:  CMDPRINTF(("pr7820: %d Display\n", ld->parameter));
2311         /* toggle or set the frame display */
2312         ld->display = (ld->parameter == -1) ? !ld->display : (ld->parameter & 1);
2313         break;
2314
2315      case 0xf2:   CMDPRINTF(("pr7820: %d Slow forward\n", ld->parameter));
2316         /* play forward at slow speed (controlled by lever on the front of the player) */
2317         if (laserdisc_ready(ld))
2318         {
2319            if (ld->parameter != -1)
2320               set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, pr7820->configspeed, ld->parameter);
2321            else
2322               set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, pr7820->configspeed, NULL_TARGET_FRAME);
2323         }
2324         break;
2325
2326      case 0xf3:  CMDPRINTF(("pr7820: %d Autostop\n", ld->parameter));
2327         /* play to a particular location and stop there */
2328         if (laserdisc_ready(ld))
2329         {
2330            INT32 targetframe = ld->parameter;
2331
2332            if (targetframe == -1)
2333               targetframe = read_16bits_from_ram_be(pr7820->ram, (pr7820->activereg * 2) % 1024);
2334            pr7820->activereg++;
2335
2336            if (targetframe > ld->last_frame)
2337               set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, targetframe);
2338            else
2339               set_state(ld, LASERDISC_SEARCHING_FRAME, PR7820_SEARCH_SPEED, targetframe);
2340         }
2341         break;
2342
2343      case 0xf4:  CMDPRINTF(("pr7820: %d Audio track 1\n", ld->parameter));
2344         /* toggle or set the state of audio channel 1 */
2345         if (ld->parameter == -1)
2346            ld->audio ^= AUDIO_CH1_ENABLE;
2347         else
2348            ld->audio = (ld->audio & ~AUDIO_CH1_ENABLE) | ((ld->parameter & 1) ? AUDIO_CH1_ENABLE : 0);
2349         break;
2350
2351      case 0xf5:   CMDPRINTF(("pr7820: %d Store\n", ld->parameter));
2352         /* store either the current frame number or an explicit value into the active register */
2353         if (ld->parameter == -1)
2354            write_16bits_to_ram_be(pr7820->ram, (pr7820->activereg * 2) % 1024, ld->last_frame);
2355         else
2356            write_16bits_to_ram_be(pr7820->ram, (pr7820->activereg * 2) % 1024, ld->parameter);
2357         pr7820->activereg++;
2358         break;
2359
2360      case 0xf6:   CMDPRINTF(("pr7820: Step forward\n"));
2361         /* step forward one frame */
2362         if (laserdisc_ready(ld))
2363         {
2364            set_state(ld, LASERDISC_STEPPING_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
2365            add_to_current_track(ld, ONE_TRACK);
2366         }
2367         break;
2368
2369      case 0xf7:  CMDPRINTF(("pr7820: %d Search\n", ld->parameter));
2370         /* search to a particular frame number */
2371         if (laserdisc_ready(ld))
2372         {
2373            INT32 targetframe = ld->parameter;
2374
2375            if (targetframe == -1)
2376               targetframe = read_16bits_from_ram_be(pr7820->ram, (pr7820->activereg * 2) % 1024);
2377            pr7820->activereg++;
2378
2379            if (targetframe == 0)
2380               targetframe = 1;
2381            set_state(ld, LASERDISC_SEARCHING_FRAME, PR7820_SEARCH_SPEED, targetframe);
2382         }
2383         break;
2384
2385      case 0xf8:   CMDPRINTF(("pr7820: %d Input\n", ld->parameter));
2386         /* wait for user input -- not implemented */
2387         break;
2388
2389      case 0xf9:   CMDPRINTF(("pr7820: Reject\n"));
2390         /* eject the disc */
2391         if (laserdisc_ready(ld))
2392         {
2393            set_state(ld, LASERDISC_EJECTING, STOP_SPEED, NULL_TARGET_FRAME);
2394            set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_EJECTED, STOP_SPEED);
2395         }
2396         break;
2397
2398      case 0xfa:   CMDPRINTF(("pr7820: %d Slow reverse\n", ld->parameter));
2399         /* play backwards at slow speed (controlled by lever on the front of the player) */
2400         if (laserdisc_ready(ld))
2401            set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, -pr7820->configspeed, (ld->parameter != -1) ? ld->parameter : NULL_TARGET_FRAME);
2402         break;
2403
2404      case 0xfb:   CMDPRINTF(("pr7820: %d Stop/Wait\n", ld->parameter));
2405         /* pause at the current location for a fixed amount of time (in 1/10ths of a second) */
2406         if (laserdisc_ready(ld))
2407         {
2408            playstate prevstate = ld->state;
2409            INT32 prevspeed = ld->curfracspeed;
2410            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
2411            if (ld->parameter != -1)
2412               set_hold_state(ld, double_to_attotime(ld->parameter * 0.1), prevstate, prevspeed);
2413         }
2414         break;
2415
2416      case 0xfc:  CMDPRINTF(("pr7820: %d Audio track 2\n", ld->parameter));
2417         /* toggle or set the state of audio channel 2 */
2418         if (ld->parameter == -1)
2419            ld->audio ^= AUDIO_CH2_ENABLE;
2420         else
2421            ld->audio = (ld->audio & ~AUDIO_CH2_ENABLE) | ((ld->parameter & 1) ? AUDIO_CH2_ENABLE : 0);
2422         break;
2423
2424      case 0xfd:  CMDPRINTF(("pr7820: Play\n"));
2425         /* begin playing at regular speed, or load the disc if it is parked */
2426         if (laserdisc_ready(ld))
2427            set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, NULL_TARGET_FRAME);
2428         else
2429         {
2430            if (ld->state == LASERDISC_PARKED)
2431            {
2432               set_state(ld, LASERDISC_SPINUP, STOP_SPEED, NULL_TARGET_FRAME);
2433               set_hold_state(ld, GENERIC_SPINUP_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
2434            }
2435            else
2436            {
2437               set_state(ld, LASERDISC_LOADING, STOP_SPEED, NULL_TARGET_FRAME);
2438               set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
2439            }
2440            reset_tracknum(ld);
2441         }
2442         break;
2443
2444      case 0xfe:   CMDPRINTF(("pr7820: Step reverse\n"));
2445         /* step backwards one frame */
2446         if (laserdisc_ready(ld))
2447         {
2448            set_state(ld, LASERDISC_STEPPING_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
2449            add_to_current_track(ld, -ONE_TRACK);
2450         }
2451         break;
2452
2453      default:   CMDPRINTF(("pr7820: %d Unknown command %02X\n", ld->parameter, data));
2454         /* unknown command */
2455         break;
2456   }
2457
2458   /* reset the parameter after executing a command */
2459   ld->parameter = -1;
2460}
2461
2462
2463/*-------------------------------------------------
2464    pr7820_ready_r - return state of the ready
2465    line
2466-------------------------------------------------*/
2467
2468static UINT8 pr7820_ready_r(laserdisc_state *ld)
2469{
2470   return (ld->state != LASERDISC_SEARCHING_FRAME) ? ASSERT_LINE : CLEAR_LINE;
2471}
2472
2473
2474/*-------------------------------------------------
2475    pr7820_status_r - return state of the ready
2476    line
2477-------------------------------------------------*/
2478
2479static UINT8 pr7820_status_r(laserdisc_state *ld)
2480{
2481   pr7820_info *pr7820 = &ld->u.pr7820;
2482
2483   /* top 3 bits reflect audio and display states */
2484   UINT8 status = (ld->audio << 6) | (ld->display << 5);
2485
2486   /* low 5 bits reflect player states */
2487
2488   /* handle program mode */
2489   if (pr7820->mode == PR7820_MODE_PROGRAM)
2490      status |= 0x0c;
2491   else
2492   {
2493      /* convert generic status into specific state equivalents */
2494      switch (ld->state)
2495      {
2496         case LASERDISC_EJECTED:               status |= 0x0d;      break;
2497         case LASERDISC_EJECTING:            status |= 0x0d;      break;
2498         case LASERDISC_LOADED:               status |= 0x01;      break;
2499         case LASERDISC_SPINUP:               status |= 0x01;      break;
2500         case LASERDISC_LOADING:               status |= 0x01;      break;
2501         case LASERDISC_PARKED:               status |= 0x01;      break;
2502
2503         case LASERDISC_SEARCHING_FRAME:         status |= 0x06;      break;
2504         case LASERDISC_SEARCH_FINISHED:         status |= 0x07;      break;
2505
2506         case LASERDISC_STOPPED:               status |= 0x03;      break;
2507         case LASERDISC_AUTOSTOPPED:            status |= 0x09;      break;
2508
2509         case LASERDISC_PLAYING_FORWARD:         status |= 0x02;      break;
2510         case LASERDISC_PLAYING_REVERSE:         status |= 0x02;      break;
2511         case LASERDISC_PLAYING_SLOW_FORWARD:   status |= 0x04;      break;
2512         case LASERDISC_PLAYING_SLOW_REVERSE:   status |= 0x05;      break;
2513         case LASERDISC_PLAYING_FAST_FORWARD:   status |= 0x02;      break;
2514         case LASERDISC_PLAYING_FAST_REVERSE:   status |= 0x02;      break;
2515         case LASERDISC_STEPPING_FORWARD:      status |= 0x03;      break;
2516         case LASERDISC_STEPPING_REVERSE:      status |= 0x03;      break;
2517         case LASERDISC_SCANNING_FORWARD:      status |= 0x02;      break;
2518         case LASERDISC_SCANNING_REVERSE:      status |= 0x02;      break;
2519         default:
2520            fatalerror("Unexpected disc state in pr7820_status_r\n");
2521            break;
2522      }
2523   }
2524   return status;
2525}
2526
2527
2528/*-------------------------------------------------
2529    pr7820_set_slow_speed - set the speed of
2530    "slow" playback, which is controlled by a
2531    slider on the device
2532-------------------------------------------------*/
2533
2534void pr7820_set_slow_speed(const device_config *device, double frame_rate_scaler)
2535{
2536   laserdisc_state *ld = get_safe_token(device);
2537   pr7820_info *pr7820 = &ld->u.pr7820;
2538   pr7820->configspeed = PLAY_SPEED * frame_rate_scaler;
2539}
2540
2541
2542
2543/***************************************************************************
2544    PIONEER PR-8210 IMPLEMENTATION
2545***************************************************************************/
2546
2547/*-------------------------------------------------
2548    pr8210_init - Pioneer PR-8210-specific
2549    initialization
2550-------------------------------------------------*/
2551
2552static void pr8210_init(laserdisc_state *ld)
2553{
2554   /* set up the write callbacks */
2555   ld->writeline[LASERDISC_LINE_CONTROL] = pr8210_control_w;   /* serial access */
2556
2557   /* do a soft reset */
2558   pr8210_soft_reset(ld);
2559}
2560
2561
2562/*-------------------------------------------------
2563    pr8210_soft_reset - Pioneer PR-8210-specific
2564    soft reset
2565-------------------------------------------------*/
2566
2567static void pr8210_soft_reset(laserdisc_state *ld)
2568{
2569   pr8210_info *pr8210 = &ld->u.pr8210;
2570
2571   ld->audio = AUDIO_CH1_ENABLE  | AUDIO_CH2_ENABLE;
2572   ld->display = 0;
2573   pr8210->firstbittime = pr8210->lastbittime = timer_get_time();
2574   pr8210->accumulator = 0;
2575   pr8210->lastcommand = 0;
2576   pr8210->seekstate = 0;
2577}
2578
2579
2580/*-------------------------------------------------
2581    pr8210_command - Pioneer PR-8210-specific
2582    command processing
2583-------------------------------------------------*/
2584
2585static void pr8210_command(laserdisc_state *ld)
2586{
2587   static const UINT8 numbers[10] = { 0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d,0x03,0x13 };
2588   pr8210_info *pr8210 = &ld->u.pr8210;
2589   UINT8 cmd = pr8210->lastcommand;
2590
2591   /* look for and process numbers */
2592   if (!process_number(ld, cmd, numbers))
2593   {
2594      switch(cmd)
2595      {
2596         case 0x00:   CMDPRINTF(("pr8210: EOC\n"));
2597            /* EOC marker - can be safely ignored */
2598            break;
2599
2600         case 0x02:   CMDPRINTF(("pr8210: Slow reverse\n"));
2601            /* slow reverse */
2602            if (laserdisc_ready(ld))
2603               set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, -PR8210_SLOW_SPEED, NULL_TARGET_FRAME);
2604            break;
2605
2606         case 0x04:   CMDPRINTF(("pr8210: Step forward\n"));
2607            /* step forward one frame */
2608            if (laserdisc_ready(ld))
2609            {
2610               set_state(ld, LASERDISC_STEPPING_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
2611               add_to_current_track(ld, ONE_TRACK);
2612            }
2613            break;
2614
2615         case 0x06 :   CMDPRINTF(("pr8210: Chapter\n"));
2616            /* chapter -- not implemented */
2617            break;
2618
2619         case 0x08:   CMDPRINTF(("pr8210: Scan forward\n"));
2620            /* scan forward */
2621            if (laserdisc_ready(ld))
2622               set_state(ld, LASERDISC_SCANNING_FORWARD, PR8210_SCAN_SPEED, NULL_TARGET_FRAME);
2623            break;
2624
2625         case 0x0a:   CMDPRINTF(("pr8210: Pause\n"));
2626            /* still picture */
2627            if (laserdisc_ready(ld))
2628               set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
2629            break;
2630
2631         case 0x0b :   CMDPRINTF(("pr8210: Frame\n"));
2632            /* frame -- not implemented */
2633            break;
2634
2635         case 0x0c:   CMDPRINTF(("pr8210: Fast reverse\n"));
2636            /* play reverse fast speed */
2637            if (laserdisc_ready(ld))
2638               set_state(ld, LASERDISC_PLAYING_FAST_REVERSE, -PR8210_FAST_SPEED, NULL_TARGET_FRAME);
2639            break;
2640
2641         case 0x0e:   CMDPRINTF(("pr8210: Ch1 toggle\n"));
2642            /* channel 1 audio toggle */
2643            ld->audio ^= AUDIO_CH1_ENABLE;
2644            break;
2645
2646         case 0x10:   CMDPRINTF(("pr8210: Fast forward\n"));
2647            /* play forward fast speed */
2648            if (laserdisc_ready(ld))
2649               set_state(ld, LASERDISC_PLAYING_FAST_FORWARD, PR8210_FAST_SPEED, NULL_TARGET_FRAME);
2650            break;
2651
2652         case 0x12:   CMDPRINTF(("pr8210: Step reverse\n"));
2653            /* step backwards one frame */
2654            if (laserdisc_ready(ld))
2655            {
2656               set_state(ld, LASERDISC_STEPPING_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
2657               add_to_current_track(ld, -ONE_TRACK);
2658            }
2659            break;
2660
2661         case 0x14:  CMDPRINTF(("pr8210: Play\n"));
2662            /* begin playing at regular speed, or load the disc if it is parked */
2663            if (laserdisc_ready(ld))
2664               set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, NULL_TARGET_FRAME);
2665            else
2666            {
2667               /* if we're already spinning up or loading, ignore */
2668               if (ld->state != LASERDISC_SPINUP && ld->state != LASERDISC_LOADING)
2669               {
2670                  if (ld->state == LASERDISC_PARKED)
2671                  {
2672                     set_state(ld, LASERDISC_SPINUP, STOP_SPEED, NULL_TARGET_FRAME);
2673                     set_hold_state(ld, GENERIC_SPINUP_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
2674                  }
2675                  else
2676                  {
2677                     set_state(ld, LASERDISC_LOADING, STOP_SPEED, NULL_TARGET_FRAME);
2678                     set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
2679                  }
2680                  reset_tracknum(ld);
2681               }
2682            }
2683            break;
2684
2685         case 0x16:   CMDPRINTF(("pr8210: Ch2 toggle\n"));
2686            /* channel 1 audio toggle */
2687            ld->audio ^= AUDIO_CH2_ENABLE;
2688            break;
2689
2690         case 0x18:   CMDPRINTF(("pr8210: Slow forward\n"));
2691            /* slow forward */
2692            if (laserdisc_ready(ld))
2693               set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, PR8210_SLOW_SPEED, NULL_TARGET_FRAME);
2694            break;
2695
2696         case 0x1a:   CMDPRINTF(("pr8210: Seek\n"));
2697            /* seek */
2698            if (pr8210->seekstate)
2699            {
2700               CMDPRINTF(("pr8210: Seeking to frame:%d\n", ld->parameter));
2701               /* we're ready to seek */
2702               set_state(ld, LASERDISC_SEARCHING_FRAME, PR8210_SEARCH_SPEED, ld->parameter);
2703               /* before seeking, we hold in the searching state for 150usec, even if seeking to the same frame */
2704               /* Us vs. Them requires at least this much "non-video" time in order to work */
2705               set_hold_state(ld, ATTOTIME_IN_MSEC(150), LASERDISC_SEARCHING_FRAME, PR8210_SEARCH_SPEED);
2706            }
2707            else
2708            {
2709               /* waiting for digits indicating position */
2710               ld->parameter = 0;
2711            }
2712            pr8210->seekstate ^= 1;
2713            break;
2714
2715         case 0x1c:   CMDPRINTF(("pr8210: Scan reverse\n"));
2716            /* scan reverse */
2717            if (laserdisc_ready(ld))
2718               set_state(ld, LASERDISC_SCANNING_REVERSE, -PR8210_SCAN_SPEED, NULL_TARGET_FRAME);
2719            break;
2720
2721         case 0x1e:   CMDPRINTF(("pr8210: Reject\n"));
2722            /* eject the disc */
2723            if (laserdisc_ready(ld))
2724            {
2725               set_state(ld, LASERDISC_EJECTING, STOP_SPEED, NULL_TARGET_FRAME);
2726               set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_EJECTED, STOP_SPEED);
2727            }
2728            break;
2729
2730         default:   CMDPRINTF(("pr8210: Unknown command %02X\n", cmd));
2731            /* unknown command */
2732            break;
2733      }
2734   }
2735}
2736
2737
2738/*-------------------------------------------------
2739    pr8210_control_w - write callback when the
2740    CONTROL line is toggled
2741-------------------------------------------------*/
2742
2743static void pr8210_control_w(laserdisc_state *ld, UINT8 data)
2744{
2745   pr8210_info *pr8210 = &ld->u.pr8210;
2746
2747   if (data == ASSERT_LINE)
2748   {
2749      attotime curtime = timer_get_time();
2750      attotime delta;
2751      int longpulse;
2752
2753      /* if we timed out, reset the accumulator */
2754      delta = attotime_sub(curtime, pr8210->firstbittime);
2755      if (delta.attoseconds > ATTOTIME_IN_USEC(25320).attoseconds)
2756      {
2757         pr8210->firstbittime = curtime;
2758         pr8210->accumulator = 0x5555;
2759//          printf("Reset accumulator\n");
2760      }
2761
2762      /* get the time difference from the last assert */
2763      /* and update our internal command time */
2764      delta = attotime_sub(curtime, pr8210->lastbittime);
2765      pr8210->lastbittime = curtime;
2766
2767      /* 0 bit delta is 1.05 msec, 1 bit delta is 2.11 msec */
2768      longpulse = (delta.attoseconds < ATTOTIME_IN_USEC(1500).attoseconds) ? 0 : 1;
2769      pr8210->accumulator = (pr8210->accumulator << 1) | longpulse;
2770
2771#if 0
2772      {
2773         int usecdiff = (int)(delta.attoseconds / ATTOSECONDS_IN_USEC(1));
2774         printf("bitdelta = %5d (%d) - accum = %04X\n", usecdiff, longpulse, pr8210->accumulator);
2775      }
2776#endif
2777
2778      /* if we have a complete command, signal it */
2779      /* a complete command is 0,0,1 followed by 5 bits, followed by 0,0 */
2780      if ((pr8210->accumulator & 0x383) == 0x80)
2781      {
2782         UINT8 newcommand = (pr8210->accumulator >> 2) & 0x1f;
2783
2784//printf("New command = %02X (last=%02X)\n", newcommand, pr8210->lastcommand);
2785
2786         /* if we got a double command, act on it */
2787         if (newcommand == pr8210->lastcommand)
2788         {
2789            pr8210_command(ld);
2790            pr8210->lastcommand = 0;
2791         }
2792         else
2793            pr8210->lastcommand = newcommand;
2794      }
2795   }
2796}
2797
2798
2799
2800/***************************************************************************
2801    SIMUTREK MODIFIED PR-8210 PLAYER IMPLEMENTATION
2802***************************************************************************/
2803
2804/*-------------------------------------------------
2805
2806    Command Set:
2807
2808    FX XX XX  : Seek to frame XXXXX
2809    01-19     : Skip forward 1-19 frames
2810    99-81     : Skip back 1-19 frames
2811    5a        : Toggle frame display
2812
2813-------------------------------------------------*/
2814
2815/*-------------------------------------------------
2816    simutrek_init - Simutrek-specific
2817    initialization
2818-------------------------------------------------*/
2819
2820static void simutrek_init(laserdisc_state *ld)
2821{
2822   /* set up the read callbacks */
2823   ld->readline[LASERDISC_LINE_STATUS] = simutrek_status_r;
2824
2825   /* set up the write callbacks */
2826   ld->writedata = simutrek_data_w;
2827
2828   /* do a soft reset */
2829   simutrek_soft_reset(ld);
2830}
2831
2832
2833/*-------------------------------------------------
2834    simutrek_soft_reset - Simutrek-specific
2835    soft reset
2836-------------------------------------------------*/
2837
2838static void simutrek_soft_reset(laserdisc_state *ld)
2839{
2840   simutrek_info *simutrek = &ld->u.simutrek;
2841
2842   ld->audio = AUDIO_CH1_ENABLE  | AUDIO_CH2_ENABLE;
2843   ld->display = 0;
2844   simutrek->firstbittime = simutrek->lastbittime = timer_get_time();
2845   simutrek->accumulator = 0;
2846   simutrek->lastcommand = 0;
2847   simutrek->seekstate = 0;
2848   simutrek->cmdcnt = 0;
2849   simutrek->cmdbytes[0] = 0;
2850   simutrek->cmdbytes[1] = 0;
2851   simutrek->cmdbytes[2] = 0;
2852}
2853
2854
2855/*-------------------------------------------------
2856    simutrek_status_r - Simutrek-specific
2857    command processing
2858-------------------------------------------------*/
2859
2860static UINT8 simutrek_status_r(laserdisc_state *ld)
2861{
2862   return (ld->state != LASERDISC_SEARCHING_FRAME) ? ASSERT_LINE : CLEAR_LINE;
2863}
2864
2865
2866/*-------------------------------------------------
2867    simutrek_data_w - Simutrek-specific
2868    data processing
2869-------------------------------------------------*/
2870
2871static void simutrek_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data)
2872{
2873   simutrek_info *simutrek = &ld->u.simutrek;
2874
2875   /* Acknowledge every command byte */
2876   if (simutrek->cmd_ack_callback != NULL)
2877      (*simutrek->cmd_ack_callback)();
2878
2879   /* Is this byte part of a multi-byte seek command? */
2880   if (simutrek->cmdcnt > 0)
2881   {
2882      CMDPRINTF(("Simutrek: Seek to frame byte %d of 3\n", simutrek->cmdcnt + 1));
2883      simutrek->cmdbytes[simutrek->cmdcnt++] = data;
2884
2885      if (simutrek->cmdcnt == 3)
2886      {
2887         int frame = ((simutrek->cmdbytes[0] & 0xf) * 10000) +
2888                  ((simutrek->cmdbytes[1] >> 4)  * 1000) +
2889                  ((simutrek->cmdbytes[1] & 0xf) * 100) +
2890                  ((simutrek->cmdbytes[2] >> 4)  * 10) +
2891                  (simutrek->cmdbytes[2] & 0xf);
2892
2893         CMDPRINTF(("Simutrek: Seek to frame %d\n", frame));
2894
2895         if (laserdisc_ready(ld))
2896            set_state(ld, LASERDISC_SEARCHING_FRAME, SIMUTREK_SEARCH_SPEED, frame);
2897
2898         simutrek->cmdcnt = 0;
2899      }
2900   }
2901   else if (data == 0)
2902   {
2903      CMDPRINTF(("Simutrek: 0 ?\n"));
2904   }
2905   else if ((data & 0xf0) == 0xf0)
2906   {
2907      CMDPRINTF(("Simutrek: Seek to frame byte 1 of 3\n"));
2908      simutrek->cmdbytes[simutrek->cmdcnt++] = data;
2909   }
2910   else if ((data >= 1) && (data <= 0x19))
2911   {
2912      int step = ((data >> 4) * 10) + (data & 0xf);
2913      CMDPRINTF(("Simutrek: Step forwards by %d frame(s)\n", step));
2914
2915      if (laserdisc_ready(ld))
2916      {
2917         set_state(ld, LASERDISC_STEPPING_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
2918         add_to_current_track(ld, step * ONE_TRACK);
2919      }
2920   }
2921   else if ((data >= 0x81) && (data <= 0x99))
2922   {
2923      int step = 100 - (((data >> 4) * 10) + (data & 0xf));
2924      CMDPRINTF(("Simutrek: Step backwards by %d frame(s)\n", step));
2925
2926      if (laserdisc_ready(ld))
2927      {
2928         set_state(ld, LASERDISC_STEPPING_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
2929         add_to_current_track(ld, step * -ONE_TRACK);
2930      }
2931   }
2932   else if (data == 0x5a)
2933   {
2934      CMDPRINTF(("Simutrek: Frame window toggle\n"));
2935      ld->display ^= 1;
2936   }
2937   else
2938   {
2939      CMDPRINTF(("Simutrek: Unknown command (%.2x)\n", data));
2940   }
2941}
2942
2943
2944/*-------------------------------------------------
2945    simutrek_set_audio_squelch - Simutrek-specific
2946    command to enable/disable audio squelch
2947-------------------------------------------------*/
2948
2949void simutrek_set_audio_squelch(const device_config *device, int state)
2950{
2951   laserdisc_state *ld = get_safe_token(device);
2952
2953   if (state == ASSERT_LINE)
2954      ld->audio |= AUDIO_SQUELCH_OVERRIDE;
2955   else
2956      ld->audio &= ~AUDIO_SQUELCH_OVERRIDE;
2957}
2958
2959
2960/*-------------------------------------------------
2961    simutrek_set_audio_squelch - Simutrek-specific
2962    command to set callback function for
2963    player/interface command acknowledge
2964-------------------------------------------------*/
2965
2966void simutrek_set_cmd_ack_callback(const device_config *device, void (*callback)(void))
2967{
2968   laserdisc_state *ld = get_safe_token(device);
2969   simutrek_info *simutrek = &ld->u.simutrek;
2970
2971   simutrek->cmd_ack_callback = callback;
2972}
2973
2974
2975
2976/***************************************************************************
2977    PIONEER LD-V1000 IMPLEMENTATION
2978***************************************************************************/
2979
2980/*-------------------------------------------------
2981    ldv1000_init - Pioneer LDV-1000-specific
2982    initialization
2983-------------------------------------------------*/
2984
2985static void ldv1000_init(laserdisc_state *ld)
2986{
2987   /* set up the write callbacks */
2988   ld->writedata = ldv1000_data_w;
2989
2990   /* set up the read callbacks */
2991   ld->readdata = ldv1000_status_r;
2992   ld->readline[LASERDISC_LINE_STATUS] = ldv1000_status_strobe_r;
2993   ld->readline[LASERDISC_LINE_COMMAND] = ldv1000_command_strobe_r;
2994
2995   /* do a soft reset */
2996   ldv1000_soft_reset(ld);
2997}
2998
2999
3000/*-------------------------------------------------
3001    ldv1000_soft_reset - Pioneer LDV-1000-specific
3002    soft reset
3003-------------------------------------------------*/
3004
3005static void ldv1000_soft_reset(laserdisc_state *ld)
3006{
3007   ldv1000_info *ldv1000 = &ld->u.ldv1000;
3008
3009   ld->audio = AUDIO_CH1_ENABLE | AUDIO_CH2_ENABLE;
3010   ld->display = FALSE;
3011   ldv1000->mode = LDV1000_MODE_STATUS;
3012   ldv1000->activereg = 0;
3013   write_16bits_to_ram_be(ldv1000->ram, 0, 1);
3014}
3015
3016
3017/*-------------------------------------------------
3018    ldv1000_data_w - write callback when the
3019    ENTER state is written
3020-------------------------------------------------*/
3021
3022static void ldv1000_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data)
3023{
3024   static const UINT8 numbers[10] = { 0x3f, 0x0f, 0x8f, 0x4f, 0x2f, 0xaf, 0x6f, 0x1f, 0x9f, 0x5f };
3025   ldv1000_info *ldv1000 = &ld->u.ldv1000;
3026
3027   /* 0xFF bytes are used for synchronization */
3028   if (data == 0xff)
3029      return;
3030
3031   /* look for and process numbers */
3032   if (process_number(ld, data, numbers))
3033      return;
3034
3035   /* handle commands */
3036   switch (data)
3037   {
3038      case 0x7f:  CMDPRINTF(("ldv1000: %d Recall\n", ld->parameter));
3039         /* set the active register */
3040         ldv1000->activereg = ld->parameter;
3041         /* should also display the register value */
3042         break;
3043
3044      case 0x20:  CMDPRINTF(("ldv1000: x0 reverse (stop) - Badlands special\n"));
3045         /* play reverse at 0 speed (stop) */
3046         if (laserdisc_ready(ld))
3047            set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
3048         break;
3049
3050      case 0x21:  CMDPRINTF(("ldv1000: x1/4 reverse - Badlands special\n"));
3051         /* play reverse at 1/4 speed */
3052         if (laserdisc_ready(ld))
3053            set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, -PLAY_SPEED / 4, NULL_TARGET_FRAME);
3054         break;
3055
3056      case 0x22:  CMDPRINTF(("ldv1000: x1/2 reverse - Badlands special\n"));
3057         /* play reverse at 1/2 speed */
3058         if (laserdisc_ready(ld))
3059            set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, -PLAY_SPEED / 2, NULL_TARGET_FRAME);
3060         break;
3061
3062      case 0x23:
3063      case 0x24:
3064      case 0x25:
3065      case 0x26:
3066      case 0x27:  CMDPRINTF(("ldv1000: x%d reverse - Badlands special\n", (data & 0x07) - 2));
3067         /* play reverse at 1-5x speed */
3068         if (laserdisc_ready(ld))
3069            set_state(ld, LASERDISC_PLAYING_FAST_REVERSE, -PLAY_SPEED * ((data & 0x07) - 2), NULL_TARGET_FRAME);
3070         break;
3071
3072      case 0xa0:  CMDPRINTF(("ldv1000: x0 forward (stop)\n"));
3073         /* play forward at 0 speed (stop) */
3074         if (laserdisc_ready(ld))
3075            set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
3076         break;
3077
3078      case 0xa1:  CMDPRINTF(("ldv1000: x1/4 forward\n"));
3079         /* play forward at 1/4 speed */
3080         if (laserdisc_ready(ld))
3081            set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, PLAY_SPEED / 4, NULL_TARGET_FRAME);
3082         break;
3083
3084      case 0xa2:  CMDPRINTF(("ldv1000: x1/2 forward\n"));
3085         /* play forward at 1/2 speed */
3086         if (laserdisc_ready(ld))
3087            set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, PLAY_SPEED / 2, NULL_TARGET_FRAME);
3088         break;
3089
3090      case 0xa3:
3091      case 0xa4:
3092      case 0xa5:
3093      case 0xa6:
3094      case 0xa7:  CMDPRINTF(("ldv1000: x%d forward\n", (data & 0x07) - 2));
3095         /* play forward at 1-5x speed */
3096         if (laserdisc_ready(ld))
3097            set_state(ld, LASERDISC_PLAYING_FAST_FORWARD, PLAY_SPEED * ((data & 0x07) - 2), NULL_TARGET_FRAME);
3098         break;
3099
3100      case 0xb1:
3101      case 0xb2:
3102      case 0xb3:
3103      case 0xb4:
3104      case 0xb5:
3105      case 0xb6:
3106      case 0xb7:
3107      case 0xb8:
3108      case 0xb9:
3109      case 0xba:  CMDPRINTF(("ldv1000: Skip forward %d0\n", data & 0x0f));
3110         /* skip forward */
3111         if (laserdisc_active(ld))
3112         {
3113            /* note that this skips tracks, not frames; the track->frame count is not 1:1 */
3114            /* in the case of 3:2 pulldown or other effects; for now, we just ignore the diff */
3115            add_to_current_track(ld, INT_TO_FRAC(10 * (data & 0x0f)));
3116         }
3117         break;
3118
3119      case 0x31:
3120      case 0x32:
3121      case 0x33:
3122      case 0x34:
3123      case 0x35:
3124      case 0x36:
3125      case 0x37:
3126      case 0x38:
3127      case 0x39:
3128      case 0x3a:  CMDPRINTF(("ldv1000: Skip backwards %d0 - Badlands special\n", data & 0x0f));
3129         /* skip backward */
3130         if (laserdisc_active(ld))
3131         {
3132            /* note that this skips tracks, not frames; the track->frame count is not 1:1 */
3133            /* in the case of 3:2 pulldown or other effects; for now, we just ignore the diff */
3134            add_to_current_track(ld, -INT_TO_FRAC(10 * (data & 0x0f)));
3135         }
3136         break;
3137
3138      case 0xbf:   CMDPRINTF(("ldv1000: %d Clear\n", ld->parameter));
3139         /* clears register display and removes pending arguments */
3140         break;
3141
3142      case 0xc2:   CMDPRINTF(("ldv1000: Get frame no.\n"));
3143         /* returns the current frame number */
3144         ldv1000->mode = LDV1000_MODE_GET_FRAME;
3145         ldv1000->readpos = 0;
3146         ldv1000->readtotal = 5;
3147         sprintf((char *)ldv1000->readbuf, "%05d", ld->last_frame);
3148         break;
3149
3150      case 0xc3:   CMDPRINTF(("ldv1000: Get 2nd display\n"));
3151         /* returns the data from the 2nd display line */
3152         ldv1000->mode = LDV1000_MODE_GET_2ND;
3153         ldv1000->readpos = 0;
3154         ldv1000->readtotal = 8;
3155         sprintf((char *)ldv1000->readbuf, "    \x1c\x1c\x1c");
3156         break;
3157
3158      case 0xc4:   CMDPRINTF(("ldv1000: Get 1st display\n"));
3159         /* returns the data from the 1st display line */
3160         ldv1000->mode = LDV1000_MODE_GET_1ST;
3161         ldv1000->readpos = 0;
3162         ldv1000->readtotal = 8;
3163         sprintf((char *)ldv1000->readbuf, "    \x1c\x1c\x1c");
3164         break;
3165
3166      case 0xc8:   CMDPRINTF(("ldv1000: Transfer memory\n"));
3167         /* returns the data from the 1st display line */
3168         ldv1000->mode = LDV1000_MODE_GET_RAM;
3169         ldv1000->readpos = 0;
3170         ldv1000->readtotal = 1024;
3171         break;
3172
3173      case 0xcc:   CMDPRINTF(("ldv1000: Load\n"));
3174         /* load program from disc -- not implemented */
3175         break;
3176
3177      case 0xcd:   CMDPRINTF(("ldv1000: Display disable\n"));
3178         /* disables the display of current command -- not implemented */
3179         break;
3180
3181      case 0xce:   CMDPRINTF(("ldv1000: Display enable\n"));
3182         /* enables the display of current command -- not implemented */
3183         break;
3184
3185      case 0xf0:   CMDPRINTF(("ldv1000: Scan forward\n"));
3186         /* scan forward */
3187         if (laserdisc_ready(ld))
3188            set_state(ld, LASERDISC_SCANNING_FORWARD, LDV1000_SCAN_SPEED, NULL_TARGET_FRAME);
3189         break;
3190
3191      case 0xf1:  CMDPRINTF(("ldv1000: %d Display\n", ld->parameter));
3192         /* toggle or set the frame display */
3193         ld->display = (ld->parameter == -1) ? !ld->display : (ld->parameter & 1);
3194         break;
3195
3196      case 0xf3:  CMDPRINTF(("ldv1000: %d Autostop\n", ld->parameter));
3197         /* play to a particular location and stop there */
3198         if (laserdisc_ready(ld))
3199         {
3200            INT32 targetframe = ld->parameter;
3201
3202            if (targetframe == -1)
3203               targetframe = read_16bits_from_ram_be(ldv1000->ram, (ldv1000->activereg++ * 2) % 1024);
3204
3205            if (targetframe > ld->last_frame)
3206               set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, targetframe);
3207            else
3208               set_state(ld, LASERDISC_SEARCHING_FRAME, PR7820_SEARCH_SPEED, targetframe);
3209            }
3210         break;
3211
3212      case 0xf4:  CMDPRINTF(("ldv1000: %d Audio track 1\n", ld->parameter));
3213         /* toggle or set the state of audio channel 1 */
3214         if (ld->parameter == -1)
3215            ld->audio ^= AUDIO_CH1_ENABLE;
3216         else
3217            ld->audio = (ld->audio & ~AUDIO_CH1_ENABLE) | ((ld->parameter & 1) ? AUDIO_CH1_ENABLE : 0);
3218         break;
3219
3220      case 0xf5:   CMDPRINTF(("ldv1000: %d Store\n", ld->parameter));
3221         /* store either the current frame number or an explicit value into the active register */
3222         if (ld->parameter == -1)
3223            write_16bits_to_ram_be(ldv1000->ram, (ldv1000->activereg * 2) % 1024, ld->last_frame);
3224         else
3225            write_16bits_to_ram_be(ldv1000->ram, (ldv1000->activereg * 2) % 1024, ld->parameter);
3226         ldv1000->activereg++;
3227         break;
3228
3229      case 0xf6:   CMDPRINTF(("ldv1000: Step forward\n"));
3230         /* step forward one frame */
3231         if (laserdisc_ready(ld))
3232         {
3233            set_state(ld, LASERDISC_STEPPING_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
3234            add_to_current_track(ld, ONE_TRACK);
3235         }
3236         break;
3237
3238      case 0xf7:  CMDPRINTF(("ldv1000: %d Search\n", ld->parameter));
3239         /* search to a particular frame number */
3240         if (laserdisc_ready(ld))
3241         {
3242            INT32 targetframe = ld->parameter;
3243
3244            if (targetframe == -1)
3245               targetframe = read_16bits_from_ram_be(ldv1000->ram, (ldv1000->activereg++ * 2) % 1024);
3246            ldv1000->activereg++;
3247
3248            set_state(ld, LASERDISC_SEARCHING_FRAME, LDV1000_SEARCH_SPEED, targetframe);
3249         }
3250         break;
3251
3252      case 0xf8:   CMDPRINTF(("ldv1000: Scan reverse\n"));
3253         /* scan reverse */
3254         if (laserdisc_ready(ld))
3255            set_state(ld, LASERDISC_SCANNING_REVERSE, -LDV1000_SCAN_SPEED, NULL_TARGET_FRAME);
3256         break;
3257
3258      case 0xf9:   CMDPRINTF(("ldv1000: Reject\n"));
3259         /* move the head to parked position, and stop rotation */
3260         set_state(ld, LASERDISC_PARKED, STOP_SPEED, NULL_TARGET_FRAME);
3261         break;
3262
3263      case 0xfb:   CMDPRINTF(("ldv1000: %d Stop/Wait\n", ld->parameter));
3264         /* pause at the current location for a fixed amount of time (in 1/10ths of a second) */
3265         if (laserdisc_ready(ld))
3266         {
3267            playstate prevstate = ld->state;
3268            INT32 prevspeed = ld->curfracspeed;
3269            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
3270            if (ld->parameter != -1)
3271               set_hold_state(ld, double_to_attotime(ld->parameter * 0.1), prevstate, prevspeed);
3272         }
3273         break;
3274
3275      case 0xfc:  CMDPRINTF(("ldv1000: %d Audio track 2\n", ld->parameter));
3276         /* toggle or set the state of audio channel 2 */
3277         if (ld->parameter == -1)
3278            ld->audio ^= AUDIO_CH2_ENABLE;
3279         else
3280            ld->audio = (ld->audio & ~AUDIO_CH2_ENABLE) | ((ld->parameter & 1) ? AUDIO_CH2_ENABLE : 0);
3281         break;
3282
3283      case 0xfd:  CMDPRINTF(("ldv1000: Play\n"));
3284         /* begin playing at regular speed, or load the disc if it is parked */
3285         if (laserdisc_ready(ld))
3286            set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, NULL_TARGET_FRAME);
3287         else
3288         {
3289            if (ld->state == LASERDISC_PARKED)
3290            {
3291               set_state(ld, LASERDISC_SPINUP, STOP_SPEED, NULL_TARGET_FRAME);
3292               set_hold_state(ld, GENERIC_SPINUP_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
3293            }
3294            else
3295            {
3296               set_state(ld, LASERDISC_LOADING, STOP_SPEED, NULL_TARGET_FRAME);
3297               set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
3298            }
3299            reset_tracknum(ld);
3300         }
3301         break;
3302
3303      case 0xfe:   CMDPRINTF(("ldv1000: Step reverse\n"));
3304         /* step backwards one frame */
3305         if (laserdisc_ready(ld))
3306         {
3307            set_state(ld, LASERDISC_STEPPING_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
3308            add_to_current_track(ld, -ONE_TRACK);
3309         }
3310         break;
3311
3312      default:   CMDPRINTF(("ldv1000: %d Unknown command %02X\n", ld->parameter, data));
3313         /* unknown command */
3314         break;
3315   }
3316
3317   /* reset the parameter after executing a command */
3318   ld->parameter = -1;
3319}
3320
3321
3322/*-------------------------------------------------
3323    ldv1000_status_strobe_r - return state of the
3324    status strobe
3325-------------------------------------------------*/
3326
3327static UINT8 ldv1000_status_strobe_r(laserdisc_state *ld)
3328{
3329   /* the status strobe is asserted (active low) 500-650usec after VSYNC */
3330   /* for a duration of 26usec; we pick 600-626usec */
3331   attotime delta = attotime_sub(timer_get_time(), ld->lastvsynctime);
3332   if (delta.attoseconds >= ATTOTIME_IN_USEC(600).attoseconds &&
3333      delta.attoseconds < ATTOTIME_IN_USEC(626).attoseconds)
3334      return ASSERT_LINE;
3335
3336   return CLEAR_LINE;
3337}
3338
3339
3340/*-------------------------------------------------
3341    ldv1000_command_strobe_r - return state of the
3342    command strobe
3343-------------------------------------------------*/
3344
3345static UINT8 ldv1000_command_strobe_r(laserdisc_state *ld)
3346{
3347   /* the command strobe is asserted (active low) 54 or 84usec after the status */
3348   /* strobe for a duration of 25usec; we pick 600+84 = 684-709usec */
3349   /* for a duration of 26usec; we pick 600-626usec */
3350   attotime delta = attotime_sub(timer_get_time(), ld->lastvsynctime);
3351   if (delta.attoseconds >= ATTOTIME_IN_USEC(684).attoseconds &&
3352      delta.attoseconds < ATTOTIME_IN_USEC(709).attoseconds)
3353      return ASSERT_LINE;
3354
3355   return CLEAR_LINE;
3356}
3357
3358
3359/*-------------------------------------------------
3360    ldv1000_status_r - return state of the ready
3361    line
3362-------------------------------------------------*/
3363
3364static UINT8 ldv1000_status_r(laserdisc_state *ld)
3365{
3366   ldv1000_info *ldv1000 = &ld->u.ldv1000;
3367   UINT8 status = 0xff;
3368
3369   /* switch off the current mode */
3370   switch (ldv1000->mode)
3371   {
3372      /* reading frame number returns 5 characters */
3373      /* reading display lines returns 8 characters */
3374      case LDV1000_MODE_GET_FRAME:
3375      case LDV1000_MODE_GET_1ST:
3376      case LDV1000_MODE_GET_2ND:
3377         assert(ldv1000->readpos < ldv1000->readtotal);
3378         status = ldv1000->readbuf[ldv1000->readpos++];
3379         if (ldv1000->readpos == ldv1000->readtotal)
3380            ldv1000->mode = LDV1000_MODE_STATUS;
3381         break;
3382
3383      /* reading RAM returns 1024 bytes */
3384      case LDV1000_MODE_GET_RAM:
3385         assert(ldv1000->readpos < ldv1000->readtotal);
3386         status = ldv1000->ram[1023 - ldv1000->readpos++];
3387         if (ldv1000->readpos == ldv1000->readtotal)
3388            ldv1000->mode = LDV1000_MODE_STATUS;
3389         break;
3390
3391      /* otherwise, we just compute a status code */
3392      default:
3393      case LDV1000_MODE_STATUS:
3394         switch (ld->state)
3395         {
3396            case LASERDISC_EJECTED:               status = 0xe0;      break;
3397            case LASERDISC_EJECTING:            status = 0x60;      break;
3398            case LASERDISC_LOADED:               status = 0xc8;      break;
3399            case LASERDISC_SPINUP:
3400            case LASERDISC_LOADING:               status = 0x48;      break;
3401            case LASERDISC_PARKED:               status = 0xfc;      break;
3402
3403            case LASERDISC_SEARCHING_FRAME:         status = 0x50;      break;
3404            case LASERDISC_SEARCH_FINISHED:         status = 0xd0;      break;
3405
3406            case LASERDISC_STOPPED:               status = 0xe5;      break;
3407            case LASERDISC_AUTOSTOPPED:            status = 0x54;      break;
3408
3409            case LASERDISC_PLAYING_FORWARD:         status = 0xe4;      break;
3410            case LASERDISC_PLAYING_REVERSE:         status = 0xe4;      break;
3411            case LASERDISC_PLAYING_SLOW_FORWARD:   status = 0xae;      break;
3412            case LASERDISC_PLAYING_SLOW_REVERSE:   status = 0xae;      break;
3413            case LASERDISC_PLAYING_FAST_FORWARD:   status = 0xae;      break;
3414            case LASERDISC_PLAYING_FAST_REVERSE:   status = 0xae;      break;
3415            case LASERDISC_STEPPING_FORWARD:      status = 0xe5;      break;
3416            case LASERDISC_STEPPING_REVERSE:      status = 0xe5;      break;
3417            case LASERDISC_SCANNING_FORWARD:      status = 0x4c;      break;
3418            case LASERDISC_SCANNING_REVERSE:      status = 0x4c;      break;
3419            default:
3420               fatalerror("Unexpected disc state in ldv1000_status_r\n");
3421               break;
3422         }
3423         break;
3424   }
3425
3426   /* bit 7 indicates our busy status */
3427   return status;
3428}
3429
3430
3431
3432/***************************************************************************
3433    SONY LDP-1450 IMPLEMENTATION
3434***************************************************************************/
3435
3436/*-------------------------------------------------
3437    ldp1450_init - Sony LDP-1450-specific
3438    initialization
3439-------------------------------------------------*/
3440
3441static void ldp1450_init(laserdisc_state *ld)
3442{
3443   /* set up the write callbacks */
3444   ld->writedata = ldp1450_data_w;
3445
3446   /* set up the read callbacks */
3447   ld->readdata = ldp1450_data_r;
3448   ld->readline[LASERDISC_LINE_DATA_AVAIL] = ldp1450_data_avail_r;
3449
3450   /* use a state changed callback */
3451   ld->statechanged = ldp1450_state_changed;
3452
3453   /* do a soft reset */
3454   ldp1450_soft_reset(ld);
3455}
3456
3457
3458/*-------------------------------------------------
3459    ldp1450_soft_reset - Sony LDP-1450-specific
3460    soft reset
3461-------------------------------------------------*/
3462
3463static void ldp1450_soft_reset(laserdisc_state *ld)
3464{
3465   ld->audio = AUDIO_CH1_ENABLE | AUDIO_CH2_ENABLE;
3466   ld->display = FALSE;
3467   set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
3468   reset_tracknum(ld);
3469}
3470
3471
3472/*-------------------------------------------------
3473    ldp1450_compute_status - compute the current
3474    status bytes on the LDP-1450
3475-------------------------------------------------*/
3476
3477static void ldp1450_compute_status(laserdisc_state *ld)
3478{
3479   /*
3480       Byte 0: LDP ready status:
3481        0x80 Ready
3482        0x82 Disc Spinning down
3483        0x86 Tray closed & no disc loaded
3484        0x8A Disc ejecting, tray opening
3485        0x92 Disc loading, tray closing
3486        0x90 Disc spinning up
3487        0xC0 Busy Searching
3488
3489       Byte 1: Error status:
3490        0x00 No error
3491        0x01 Focus unlock
3492        0x02 Communication Error
3493
3494       Byte 2: Disc/motor status:
3495        0x01 Motor Off (disc spinning down or tray opening/ed)
3496        0x02 Tray closed & motor Off (no disc loaded)
3497        0x11 Motor On
3498
3499       Byte 3: Command/argument status:
3500        0x00 Normal
3501        0x01 Relative search or Mark Set pending (Enter not sent)
3502        0x03 Search pending (Enter not sent)
3503        0x05 Repeat pending (Enter not sent) or Memory Search in progress
3504        0x80 FWD or REV Step
3505
3506       Byte 4: Playback mode:
3507        0x00 Searching, Motor On (spinning up), motor Off (spinning down), tray opened/ing (no motor phase lock)
3508        0x01 FWD Play
3509        0x02 FWD Fast
3510        0x04 FWD Slow
3511        0x08 FWD Step
3512        0x10 FWD Scan
3513        0x20 Still
3514        0x81 REV Play
3515        0x82 REV Fast
3516        0x84 REV Slow
3517        0x88 REV Step
3518        0x90 REV Scan
3519    */
3520
3521   ldp1450_info *ldp1450 = &ld->u.ldp1450;
3522   UINT32 statusbytes = 0;
3523
3524   switch (ld->state)
3525   {
3526      case LASERDISC_EJECTED:               statusbytes = 0x86000200;   break;
3527      case LASERDISC_EJECTING:            statusbytes = 0x8a000100;   break;
3528      case LASERDISC_LOADED:               statusbytes = 0x80000100;   break;
3529      case LASERDISC_SPINUP:
3530      case LASERDISC_LOADING:               statusbytes = 0x92001100;   break;
3531      case LASERDISC_PARKED:               statusbytes = 0x80000100;   break;
3532      case LASERDISC_SEARCHING_FRAME:         statusbytes = 0xc0001100;   break;
3533
3534      case LASERDISC_SEARCH_FINISHED:
3535      case LASERDISC_STOPPED:
3536      case LASERDISC_AUTOSTOPPED:            statusbytes = 0x80001120;   break;
3537
3538      case LASERDISC_PLAYING_FORWARD:         statusbytes = 0x80001101;   break;
3539      case LASERDISC_PLAYING_REVERSE:         statusbytes = 0x80001181;   break;
3540      case LASERDISC_PLAYING_SLOW_FORWARD:   statusbytes = 0x80001104;   break;
3541      case LASERDISC_PLAYING_SLOW_REVERSE:   statusbytes = 0x80001184;   break;
3542      case LASERDISC_PLAYING_FAST_FORWARD:   statusbytes = 0x80001102;   break;
3543      case LASERDISC_PLAYING_FAST_REVERSE:   statusbytes = 0x80001182;   break;
3544      case LASERDISC_STEPPING_FORWARD:      statusbytes = 0x80001108;   break;
3545      case LASERDISC_STEPPING_REVERSE:      statusbytes = 0x80001188;   break;
3546      case LASERDISC_SCANNING_FORWARD:      statusbytes = 0x80001110;   break;
3547      case LASERDISC_SCANNING_REVERSE:      statusbytes = 0x80001190;   break;
3548
3549      default:
3550         fatalerror("Unexpected disc state in ldp1450_compute_status\n");
3551         break;
3552   }
3553
3554   /* copy in the result bytes */
3555   ldp1450->readtotal = 0;
3556   ldp1450->readbuf[ldp1450->readtotal++] = (statusbytes >> 24) & 0xff;
3557   ldp1450->readbuf[ldp1450->readtotal++] = (statusbytes >> 16) & 0xff;
3558   ldp1450->readbuf[ldp1450->readtotal++] = (statusbytes >> 8) & 0xff;
3559   switch (ld->command)
3560   {
3561      case 0x43:   ldp1450->readbuf[ldp1450->readtotal++] = 0x03;   break;
3562      default:   ldp1450->readbuf[ldp1450->readtotal++] = 0x00;   break;
3563   }
3564   ldp1450->readbuf[ldp1450->readtotal++] = (statusbytes >> 0) & 0xff;
3565}
3566
3567
3568/*-------------------------------------------------
3569    ldp1450_data_w - write callback when the
3570    ENTER state is written
3571-------------------------------------------------*/
3572
3573static void ldp1450_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data)
3574{
3575   static const UINT8 numbers[10] = { 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39 };
3576   ldp1450_info *ldp1450 = &ld->u.ldp1450;
3577
3578   /* by default, we return an ack on each command */
3579   ldp1450->readpos = ldp1450->readtotal = 0;
3580   ldp1450->readbuf[ldp1450->readtotal++] = 0x0a;
3581
3582   /* look for and process numbers */
3583   if (process_number(ld, data, numbers))
3584   {
3585      CMDPRINTF(("%c", data));
3586      return;
3587   }
3588
3589   /* handle commands */
3590   switch (data)
3591   {
3592      case 0x24:  CMDPRINTF(("ldp1450: Audio Mute On\n"));
3593         /* mute audio */
3594         ld->audio |= AUDIO_EXPLICIT_MUTE;
3595         break;
3596
3597      case 0x25:  CMDPRINTF(("ldp1450: Audio Mute Off\n"));
3598         /* unmute audio */
3599         ld->audio &= ~AUDIO_EXPLICIT_MUTE;
3600         break;
3601
3602      case 0x26:  CMDPRINTF(("ldp1450: Video Mute Off\n"));
3603         /* mute video -- not implemented */
3604         break;
3605
3606      case 0x27:  CMDPRINTF(("ldp1450: Video Mute On\n"));
3607         /* unmute video -- not implemented */
3608         break;
3609
3610      case 0x28:  CMDPRINTF(("ldp1450: PSC Enable\n"));
3611         /* enable Picture Stop Codes (PSC) -- not implemented */
3612         break;
3613
3614      case 0x29:  CMDPRINTF(("ldp1450: PSC Disable\n"));
3615         /* disable Picture Stop Codes (PSC) -- not implemented */
3616         break;
3617
3618      case 0x2a:   CMDPRINTF(("ldp1450: %d Eject\n", ld->parameter));
3619         /* eject the disc */
3620         if (laserdisc_ready(ld))
3621         {
3622            set_state(ld, LASERDISC_EJECTING, STOP_SPEED, NULL_TARGET_FRAME);
3623            set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_EJECTED, STOP_SPEED);
3624         }
3625         break;
3626
3627      case 0x2b:   CMDPRINTF(("ldp1450: %d Step forward\n", ld->parameter));
3628         /* step forward one frame */
3629         if (laserdisc_ready(ld))
3630         {
3631            set_state(ld, LASERDISC_STEPPING_FORWARD, STOP_SPEED, NULL_TARGET_FRAME);
3632            add_to_current_track(ld, ONE_TRACK);
3633         }
3634         break;
3635
3636      case 0x2c:   CMDPRINTF(("ldp1450: %d Step reverse\n", ld->parameter));
3637         /* step backwards one frame */
3638         if (laserdisc_ready(ld))
3639         {
3640            set_state(ld, LASERDISC_STEPPING_REVERSE, STOP_SPEED, NULL_TARGET_FRAME);
3641            add_to_current_track(ld, -ONE_TRACK);
3642         }
3643         break;
3644
3645      case 0x2d:  CMDPRINTF(("ldp1450: %d Search multiple tracks forward\n", ld->parameter));
3646         /* enable Picture Stop Codes (PSC) -- not implemented */
3647         break;
3648
3649      case 0x2e:  CMDPRINTF(("ldp1450: %d Search multiple tracks reverse\n", ld->parameter));
3650         /* disable Picture Stop Codes (PSC) -- not implemented */
3651         break;
3652
3653      case 0x3a:  CMDPRINTF(("ldp1450: %d Play\n", ld->parameter));
3654         /* begin playing at regular speed, or load the disc if it is parked */
3655         if (laserdisc_ready(ld))
3656            set_state(ld, LASERDISC_PLAYING_FORWARD, PLAY_SPEED, NULL_TARGET_FRAME);
3657         else
3658         {
3659            if (ld->state == LASERDISC_PARKED)
3660            {
3661               set_state(ld, LASERDISC_SPINUP, STOP_SPEED, NULL_TARGET_FRAME);
3662               set_hold_state(ld, GENERIC_SPINUP_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
3663            }
3664            else
3665            {
3666               set_state(ld, LASERDISC_LOADING, STOP_SPEED, NULL_TARGET_FRAME);
3667               set_hold_state(ld, GENERIC_LOAD_TIME, LASERDISC_PLAYING_FORWARD, PLAY_SPEED);
3668            }
3669            reset_tracknum(ld);
3670         }
3671         break;
3672
3673      case 0x3b:  CMDPRINTF(("ldp1450: %d Fast forward play\n", ld->parameter));
3674         /* play forward fast speed */
3675         if (laserdisc_ready(ld))
3676            set_state(ld, LASERDISC_PLAYING_FAST_FORWARD, LDP1450_FAST_SPEED, NULL_TARGET_FRAME);
3677         break;
3678
3679      case 0x3c:  CMDPRINTF(("ldp1450: %d Slow forward play\n", ld->parameter));
3680         /* play forward slow speed */
3681         if (laserdisc_ready(ld))
3682            set_state(ld, LASERDISC_PLAYING_SLOW_FORWARD, LDP1450_SLOW_SPEED, NULL_TARGET_FRAME);
3683         break;
3684
3685      case 0x3d:  CMDPRINTF(("ldp1450: %d Variable forward play\n", ld->parameter));
3686         /* play forward variable speed */
3687         if (laserdisc_ready(ld))
3688         {
3689            set_state(ld, LASERDISC_STEPPING_FORWARD, LDP1450_STEP_SPEED, NULL_TARGET_FRAME);
3690            ld->command = 0x3d;
3691         }
3692         break;
3693
3694      case 0x3e:  CMDPRINTF(("ldp1450: %d Scan forward\n", ld->parameter));
3695         /* scan forward */
3696         if (laserdisc_ready(ld))
3697            set_state(ld, LASERDISC_SCANNING_FORWARD, LDP1450_SCAN_SPEED, NULL_TARGET_FRAME);
3698         break;
3699
3700      case 0x3f:   CMDPRINTF(("ldp1450: Stop\n"));
3701         /* pause at the current location */
3702         if (laserdisc_ready(ld))
3703            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
3704         break;
3705
3706      case 0x40:  CMDPRINTF((" ... Enter\n"));
3707         /* Enter -- execute command with parameter */
3708         switch (ld->command)
3709         {
3710            case 0x3d:   /* forward variable speed */
3711               if (ld->parameter != 0)
3712                  ld->curfracspeed = PLAY_SPEED / ld->parameter;
3713               break;
3714
3715            case 0x43:   /* search */
3716               set_state(ld, LASERDISC_SEARCHING_FRAME, LDP1450_SEARCH_SPEED, ld->parameter);
3717               break;
3718
3719            case 0x4d:   /* reverse variable speed */
3720               if (ld->parameter != 0)
3721                  ld->curfracspeed = -PLAY_SPEED / ld->parameter;
3722               break;
3723
3724            default: CMDPRINTF(("Unknown command: %02X\n", ld->command));
3725               break;
3726         }
3727         break;
3728
3729      case 0x41:  CMDPRINTF(("ldp1450: %d Clear entry\n", ld->parameter));
3730         /* Clear entry */
3731         break;
3732
3733      case 0x42:  CMDPRINTF(("ldp1450: %d Menu\n", ld->parameter));
3734         /* Menu -- not implemented */
3735         break;
3736
3737      case 0x43:  CMDPRINTF(("ldp1450: Search ... "));
3738         /* search to a particular frame number */
3739         if (laserdisc_ready(ld))
3740         {
3741            ld->command = data;
3742
3743            /* Note that the disc stops as soon as the search command is issued */
3744            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
3745         }
3746         break;
3747
3748      case 0x44:  CMDPRINTF(("ldp1450: %d Repeat\n", ld->parameter));
3749         /* Repeat -- not implemented */
3750         break;
3751
3752      case 0x46:  CMDPRINTF(("ldp1450: Ch1 On\n"));
3753         /* channel 1 audio on */
3754         ld->audio |= AUDIO_CH1_ENABLE;
3755         break;
3756
3757      case 0x47:  CMDPRINTF(("ldp1450: Ch1 Off\n"));
3758         /* channel 1 audio off */
3759         ld->audio &= ~AUDIO_CH1_ENABLE;
3760         break;
3761
3762      case 0x48:  CMDPRINTF(("ldp1450: Ch2 On\n"));
3763         /* channel 1 audio on */
3764         ld->audio |= AUDIO_CH2_ENABLE;
3765         break;
3766
3767      case 0x49:  CMDPRINTF(("ldp1450: Ch2 Off\n"));
3768         /* channel 1 audio off */
3769         ld->audio &= ~AUDIO_CH2_ENABLE;
3770         break;
3771
3772      case 0x4a:  CMDPRINTF(("ldp1450: %d Reverse Play\n", ld->parameter));
3773         /* begin playing at regular speed, or load the disc if it is parked */
3774         if (laserdisc_ready(ld))
3775            set_state(ld, LASERDISC_PLAYING_REVERSE, -PLAY_SPEED, NULL_TARGET_FRAME);
3776         break;
3777
3778      case 0x4b:  CMDPRINTF(("ldp1450: %d Fast reverse play\n", ld->parameter));
3779         /* play reverse fast speed */
3780         if (laserdisc_ready(ld))
3781            set_state(ld, LASERDISC_PLAYING_FAST_REVERSE, -LDP1450_FAST_SPEED, NULL_TARGET_FRAME);
3782         break;
3783
3784      case 0x4c:  CMDPRINTF(("ldp1450: %d Slow reverse play\n", ld->parameter));
3785         /* play reverse slow speed */
3786         if (laserdisc_ready(ld))
3787            set_state(ld, LASERDISC_PLAYING_SLOW_REVERSE, -LDP1450_SLOW_SPEED, NULL_TARGET_FRAME);
3788         break;
3789
3790      case 0x4d:  CMDPRINTF(("ldp1450: %d Variable reverse play\n", ld->parameter));
3791         /* play reverse variable speed */
3792         if (laserdisc_ready(ld))
3793         {
3794            set_state(ld, LASERDISC_STEPPING_REVERSE, -LDP1450_STEP_SPEED, NULL_TARGET_FRAME);
3795            ld->command = 0x4d;
3796         }
3797         break;
3798
3799      case 0x4e:  CMDPRINTF(("ldp1450: %d Scan reverse\n", ld->parameter));
3800         /* play forward variable speed */
3801         if (laserdisc_ready(ld))
3802            set_state(ld, LASERDISC_SCANNING_REVERSE, -LDP1450_SCAN_SPEED, NULL_TARGET_FRAME);
3803         break;
3804
3805      case 0x4f:   CMDPRINTF(("ldp1450: %d Still\n", ld->parameter));
3806         /* still picture */
3807         if (laserdisc_ready(ld))
3808            set_state(ld, LASERDISC_STOPPED, STOP_SPEED, NULL_TARGET_FRAME);
3809         break;
3810
3811      case 0x50:  CMDPRINTF(("ldp1450: Index On\n"));
3812         /* index on -- not implemented */
3813         break;
3814
3815      case 0x51:  CMDPRINTF(("ldp1450: Index Off\n"));
3816         /* index off -- not implemented */
3817         break;
3818
3819      case 0x55:  CMDPRINTF(("ldp1450: %d Set to frame number mode\n", ld->parameter));
3820         /* set to frame number mode -- not implemented */
3821         break;
3822
3823      case 0x56:  CMDPRINTF(("ldp1450: %d Clear all\n", ld->parameter));
3824         /* clear all */
3825         ldp1450_soft_reset(ld);
3826         break;
3827
3828      case 0x5a:  CMDPRINTF(("ldp1450: %d Memory\n", ld->parameter));
3829         /* memorize current position -- not implemented */
3830         break;
3831
3832      case 0x5b:  CMDPRINTF(("ldp1450: %d Memory Search\n", ld->parameter));
3833         /* locate memorized position -- not implemented */
3834         break;
3835
3836      case 0x60:  CMDPRINTF(("ldp1450: %d Address Inquire\n", ld->parameter));
3837         /* inquire for current address */
3838         ldp1450->readtotal = 0;
3839         ldp1450->readbuf[ldp1450->readtotal++] = '0' + (ld->last_frame / 10000) % 10;
3840         ldp1450->readbuf[ldp1450->readtotal++] = '0' + (ld->last_frame / 1000) % 10;
3841         ldp1450->readbuf[ldp1450->readtotal++] = '0' + (ld->last_frame / 100) % 10;
3842         ldp1450->readbuf[ldp1450->readtotal++] = '0' + (ld->last_frame / 10) % 10;
3843         ldp1450->readbuf[ldp1450->readtotal++] = '0' + (ld->last_frame / 1) % 10;
3844         break;
3845
3846      case 0x61:  CMDPRINTF(("ldp1450: %d Continue\n", ld->parameter));
3847         /* resume the mode prior to still -- not implemented */
3848         break;
3849
3850      case 0x62:  CMDPRINTF(("ldp1450: Motor On\n"));
3851         /* motor on -- not implemented */
3852         break;
3853
3854      case 0x63:  CMDPRINTF(("ldp1450: Motor Off\n"));
3855         /* motor off -- not implemented */
3856         break;
3857
3858      case 0x67:  CMDPRINTF(("ldp1450: %d Status Inquire\n", ld->parameter));
3859         /* inquire status of player */
3860         ldp1450_compute_status(ld);
3861         break;
3862
3863      case 0x69:  CMDPRINTF(("ldp1450: %d Chapter Mode\n", ld->parameter));
3864         /* set to chapter number mode -- not implemented */
3865         break;
3866
3867      case 0x6e:  CMDPRINTF(("ldp1450: CX On\n"));
3868         /* CX noise reduction on -- not implemented */
3869         break;
3870
3871      case 0x6f:  CMDPRINTF(("ldp1450: CX Off\n"));
3872         /* CX noise reduction off -- not implemented */
3873         break;
3874
3875      case 0x71:  CMDPRINTF(("ldp1450: %d Non-CF Play\n", ld->parameter));
3876         /* disengage color framing -- not implemented */
3877         break;
3878
3879      case 0x72:  CMDPRINTF(("ldp1450: %d ROM Version\n", ld->parameter));
3880         /* inquire ROM version -- not implemented */
3881         break;
3882
3883      case 0x73:  CMDPRINTF(("ldp1450: %d Mark Set\n", ld->parameter));
3884         /* set mark position -- not implemented */
3885         break;
3886
3887      case 0x74:  CMDPRINTF(("ldp1450: Eject Enable On\n"));
3888         /* activate eject function -- not implemented */
3889         break;
3890
3891      case 0x75:  CMDPRINTF(("ldp1450: Eject Disable Off\n"));
3892         /* deactivate eject function -- not implemented */
3893         break;
3894
3895      case 0x76:  CMDPRINTF(("ldp1450: %d Chapter Inquire\n", ld->parameter));
3896         /* inquire current chapter -- not implemented */
3897         break;
3898
3899      case 0x79:  CMDPRINTF(("ldp1450: %d User Code Inquire\n", ld->parameter));
3900         /* inquire user's code -- not implemented */
3901         break;
3902
3903      case 0x80:  CMDPRINTF(("ldp1450: %d User Index Control\n", ld->parameter));
3904         /* set user defined index -- not implemented */
3905         break;
3906
3907      case 0x81:  CMDPRINTF(("ldp1450: Activate user defined index\n"));
3908         /* activate eject function -- not implemented */
3909         break;
3910
3911      case 0x82:  CMDPRINTF(("ldp1450: Deactivate user defined index\n"));
3912         /* deactivate eject function -- not implemented */
3913         break;
3914
3915      default:   CMDPRINTF(("ldp1450: %d Unknown command %02X\n", ld->parameter, data));
3916         /* unknown command -- respond with a NAK */
3917         ldp1450->readtotal = 0;
3918         ldp1450->readbuf[ldp1450->readtotal++] = 0x0b;
3919         break;
3920   }
3921
3922   /* reset the parameter after executing a command */
3923   ld->parameter = -1;
3924}
3925
3926
3927/*-------------------------------------------------
3928    ldp1450_data_avail_r - return ASSERT_LINE if
3929    serial data is available
3930-------------------------------------------------*/
3931
3932static UINT8 ldp1450_data_avail_r(laserdisc_state *ld)
3933{
3934   ldp1450_info *ldp1450 = &ld->u.ldp1450;
3935   return (ldp1450->readpos < ldp1450->readtotal) ? ASSERT_LINE : CLEAR_LINE;
3936}
3937
3938
3939/*-------------------------------------------------
3940    ldp1450_data_r - return data from the player
3941-------------------------------------------------*/
3942
3943static UINT8 ldp1450_data_r(laserdisc_state *ld)
3944{
3945   ldp1450_info *ldp1450 = &ld->u.ldp1450;
3946
3947   if (ldp1450->readpos < ldp1450->readtotal)
3948      return ldp1450->readbuf[ldp1450->readpos++];
3949   return 0xff;
3950}
3951
3952
3953/*-------------------------------------------------
3954    ldp1450_state_changed - Sony LDP-1450-specific
3955    state changed callback
3956-------------------------------------------------*/
3957
3958static void ldp1450_state_changed(laserdisc_state *ld, UINT8 oldstate)
3959{
3960   ldp1450_info *ldp1450 = &ld->u.ldp1450;
3961
3962   /* look for searching -> search finished state */
3963   if (ld->state == LASERDISC_SEARCH_FINISHED && oldstate == LASERDISC_SEARCHING_FRAME)
3964   {
3965      ldp1450->readpos = ldp1450->readtotal = 0;
3966      ldp1450->readbuf[ldp1450->readtotal++] = 0x01;
3967   }
3968}
3969
3970
3971
3972/***************************************************************************
3973    PHILPS 22VP932 IMPLEMENTATION
3974***************************************************************************/
3975
3976/*-------------------------------------------------
3977    vp932_init - Philips 22VP932-specific
3978    initialization
3979-------------------------------------------------*/
3980
3981static void vp932_init(laserdisc_state *ld)
3982{
3983   /* set up the write callbacks */
3984   ld->writedata = vp932_data_w;
3985
3986   /* set up the read callbacks */
3987   ld->readdata = vp932_data_r;
3988   ld->readline[LASERDISC_LINE_DATA_AVAIL] = vp932_data_avail_r;
3989
3990   /* use a state changed callback */
3991   ld->statechanged = vp932_state_changed;
3992
3993   /* do a soft reset */
3994   vp932_soft_reset(ld);
3995}
3996
3997
3998/*-------------------------------------------------
3999    vp932_soft_reset - Philips 22VP932-specific
4000    soft reset
4001-------------------------------------------------*/
4002
4003static void vp932_soft_reset(laserdisc_state *ld)
4004{
4005   vp932_info *vp932 = &ld->u.vp932;
4006
4007   ld->audio = AUDIO_CH1_ENABLE  | AUDIO_CH2_ENABLE;
4008   ld->display = 0;
4009
4010   /* reset the pending count */
4011   vp932->incount = 0;
4012   vp932->outcount = 0;
4013}
4014
4015
4016/*-------------------------------------------------
4017    vp932_data_w - write callback when data is
4018    written
4019-------------------------------------------------*/
4020
4021static void vp932_data_w(laserdisc_state *ld, UINT8 prev, UINT8 data)
4022{
4023   vp932_info *vp932 = &ld->u.vp932;
4024
4025   /* ignore 0's */
4026   if (data == 0x00)
4027      return;
4028
4029   /* if this isn't a CR, just accumulate it */
4030   if (data != 0x0d)
4031   {
4032      if (vp932->incount < ARRAY_LENGTH(vp932->inbuffer))
4033         vp932->inbuffer[vp932->incount++] = data;
4034   }
4035
4036   /* otherwise, execute the command */
4037   else
4038   {
4039      vp932->inbuffer[vp932->incount] = 0;
4040      CMDPRINTF(("22vp932: %s\n", vp932->inbuffer));
4041
4042      switch (vp932->inbuffer[vp932->incount - 1])
4043      {
4044         case 'R':   /* seek */
4045            if (laserdisc_ready(ld))
4046            {
4047               INT32 targetframe = 0, i;
4048
4049               for (i = 0; i < vp932->incount - 1; i++)
4050                  if (vp932->inbuffer[i] >= '0' && vp932->inbuffer[i] <= '9')
4051                     targetframe = (targetframe * 10) + (vp932->inbuffer[i] - '0');
4052               set_state(ld, LASERDISC_SEARCHING_FRAME, VP932_SEARCH_SPEED, targetframe);
4053
4054               vp932->outcount = 0;
4055               vp932->outbuffer[vp932->outcount++] = 'A';
4056               vp932->outbuffer[vp932->outcount++] = '0';
4057               vp932->outbuffer[vp932->outcount++] = 0x0d;
4058            }
4059            break;
4060      }
4061
4062      /* reset the command buffer */
4063      vp932->incount = 0;
4064   }
4065}
4066
4067
4068/*-------------------------------------------------
4069    vp932_data_r - read callback when data is
4070    returned
4071-------------------------------------------------*/
4072
4073static UINT8 vp932_data_r(laserdisc_state *ld)
4074{
4075   vp932_info *vp932 = &ld->u.vp932;
4076   UINT8 result = 0;
4077
4078   /* grab data if we can */
4079   if (vp932->outcount > 0)
4080   {
4081      result = vp932->outbuffer[0];
4082      if (--vp932->outcount > 0)
4083         memmove(&vp932->outbuffer[0], &vp932->outbuffer[1], vp932->outcount);
4084   }
4085
4086   return result;
4087}
4088
4089
4090/*-------------------------------------------------
4091    vp932_data_avail_r - return ASSERT_LINE if
4092    serial data is available
4093-------------------------------------------------*/
4094
4095static UINT8 vp932_data_avail_r(laserdisc_state *ld)
4096{
4097   vp932_info *vp932 = &ld->u.vp932;
4098   return (vp932->outcount > 0) ? ASSERT_LINE : CLEAR_LINE;
4099}
4100
4101
4102/*-------------------------------------------------
4103    vp932_state_changed - Sony LDP-1450-specific
4104    state changed callback
4105-------------------------------------------------*/
4106
4107static void vp932_state_changed(laserdisc_state *ld, UINT8 oldstate)
4108{
4109   vp932_info *vp932 = &ld->u.vp932;
4110
4111   /* look for searching -> search finished state */
4112   if (ld->state == LASERDISC_SEARCH_FINISHED && oldstate == LASERDISC_SEARCHING_FRAME)
4113   {
4114      vp932->outcount = 0;
4115      vp932->outbuffer[vp932->outcount++] = 'A';
4116      vp932->outbuffer[vp932->outcount++] = '0';
4117      vp932->outbuffer[vp932->outcount++] = 0x0d;
4118   }
4119}
src/emu/sound/namcona.c
r3367r3368
1/*
2    Namco NA1/2 Sound Hardware
3
4    PCM samples and sound sequencing metadata are written by the main CPU to
5    shared RAM.
6
7    The sound CPU's type is unknown, though it appears to be little endian.
8    It has an internal BIOS.
9
10    RAM[0x820]:         song select
11    RAM[0x822]:         song control (fade?)
12    RAM[0x824..0x89e]:
13        Even addresses are used to select the sound effect.
14        0x40 is written to odd addresses as a signal to play the requested sound.
15
16    Metadata vectors:
17    addr  sample
18    0000: 0012   // table of addresses for each VOX sequence
19    0002: 07e4   // table of wave records (5 words each record)
20    0004: 0794   // unknown table (5 words each record)
21    0006: 0000   // unknown (always zero?)
22    0008: 0102   // unknown address table
23    000a: 0384   // unknown address table
24    000c: 0690   // unknown chunk
25    000e: 07bc   // unknown table (5 words each record)
26    0010: 7700   // unknown
27    0012: addresses for each song sequence start here
28
29    Known issues:
30    - many opcodes are ignored or implemented imperfectly
31    - the metadata contains several mystery tables
32*/
33
34#include <math.h>
35#include "sndintrf.h"
36#include "streams.h"
37#include "namcona.h"
38
39#define kTwelfthRootTwo 1.059463094
40#define FIXED_POINT_SHIFT (10) /* for mixing */
41#define MAX_VOICE 16
42#define MAX_SEQUENCE_VOICE 32
43#define MAX_SEQUENCE  0x40
44#define MAX_SEQUENCE_RECURSION 4 /* ? */
45#define SAMPLE_RATE_BASE (42667*2)
46
47struct voice
48{
49   INT32 bActive;
50
51   INT32 flags;
52   INT32 start; /* fixed point */
53   INT32 end;   /* fixed point */
54   INT32 loop;  /* fixed point */
55   INT32 baseFreq;
56   INT32 bank;
57
58   INT32 delta; /* fixed point */
59   INT32 pos;
60   INT32 note;
61   INT32 preNote;
62   INT32 volume;
63   INT32 pan;
64   INT32 leftVolume;
65   INT32 rightVolume;
66   INT32 dnote;
67   INT32 detune;
68   INT32 ignoreCount;
69   INT32 delay;
70   INT32 delayCount;
71   INT32 freqCtrlTableNo;
72   INT32 freqCtrlTable;
73   INT32 freqCtrlSpeed;
74   INT32 freqCtrlAmp;
75   INT32 freqCtrlPointer;
76   INT32 freqCtrlCounter;
77   INT32 freqCtrlFreq;
78   INT32 volCtrlTable;
79   INT32 volCtrlCount;
80   INT32 volCtrlPointer;
81   INT32 volCtrlCounter;
82   INT32 volCtrlSpeed;
83   INT32 volCtrlVol;
84   INT32 volCtrlVolEnd;
85   INT32 panCtrlTable;
86   INT32 panCtrlSpeed;
87   INT32 panCtrlCounter;
88   INT32 panCtrlEnable;
89   INT32 portament;
90   INT32 portamentSpeed;
91   INT32 portamentNote;
92};
93
94struct sequence
95{
96   UINT8 volume;
97   UINT8 reg2; /* master freq? */
98   UINT8 tempo;
99   int addr;
100   int pause;
101   int channel[8];
102   int stackData[MAX_SEQUENCE_RECURSION]; /* used for sub-sequences */
103   int stackSize;
104   int count; /* used for "repeat" opcode */
105   int count2;
106   int count3;
107};
108
109struct namcona
110{
111   int mSampleRate;
112   sound_stream * mStream;
113   INT16 *mpMixerBuffer;
114   INT32 *mpPitchTable;
115   UINT16 *mpROM;
116   UINT16 *mpMetaData;
117   struct sequence mSequence[MAX_SEQUENCE];
118   struct voice mVoice[MAX_SEQUENCE_VOICE];
119};
120
121static const UINT16 VolCtrlSpeedTable[0x80] =
122{
123   0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0009,
124   0x000b, 0x000d, 0x000f, 0x0011, 0x0013, 0x0015, 0x0017, 0x0019,
125   0x001b, 0x001d, 0x001f, 0x0022, 0x0024, 0x0027, 0x002a, 0x002d,
126   0x0030, 0x0033, 0x0037, 0x003b, 0x0040, 0x0044, 0x0049, 0x004f,
127   0x0054, 0x005a, 0x0061, 0x0068, 0x0070, 0x0078, 0x0081, 0x008a,
128   0x0094, 0x009f, 0x00aa, 0x00b7, 0x00c4, 0x00d2, 0x00e1, 0x00f2,
129   0x0103, 0x0116, 0x012a, 0x0140, 0x0157, 0x0170, 0x018b, 0x01ab,
130   0x01c7, 0x01e8, 0x020b, 0x0231, 0x025a, 0x0285, 0x02b4, 0x02e6,
131   0x031c, 0x0356, 0x0394, 0x03d6, 0x041d, 0x046a, 0x04bc, 0x0514,
132   0x0572, 0x05d7, 0x0644, 0x06b8, 0x0735, 0x07ba, 0x084a, 0x08e4,
133   0x0989, 0x0a3a, 0x0af8, 0x0bc3, 0x0c9e, 0x0d88, 0x0e83, 0x0f91,
134   0x10b2, 0x11e8, 0x1334, 0x1498, 0x1617, 0x17b1, 0x1969, 0x1b40,
135   0x1d3a, 0x1f59, 0x219f, 0x240f, 0x26ac, 0x297a, 0x2c7c, 0x2fb6,
136   0x332b, 0x36e1, 0x3adc, 0x3f20, 0x43b4, 0x489d, 0x4de1, 0x5386,
137   0x5995, 0x6014, 0x670b, 0x6e84, 0x7687, 0x7f1f, 0x8857, 0x923a,
138   0x9cd4, 0xa833, 0xb465, 0xc17a, 0xcf81, 0xde8d, 0xeeb0, 0xffff
139};
140
141
142/**
143 * Given a sequence, return a pointer to the associated 16 bit word in shared RAM.
144 * The 16 bits are interpretted as follows:
145 * xxxxxxxx-------- index into sequence table (selects song/sample)
146 * --------x------- 1 if sequence is active/playing
147 * ---------x------ 1 if the main CPU has written a new sound command
148 * ----------xxxxxx unknown/unused
149 */
150static UINT16 *
151GetSequenceStatusAddr( struct namcona *chip, struct sequence *pSeq )
152{
153   int offs = pSeq - chip->mSequence;
154   return &chip->mpROM[0x820/2+offs];
155}
156
157static void
158Silence( struct namcona *chip )
159{
160   int i;
161   for( i=0; i<MAX_SEQUENCE_VOICE; i++ )
162   {
163      chip->mVoice[i].bActive = 0;
164   }
165   for( i=0; i<MAX_SEQUENCE; i++ )
166   {
167      UINT16 *pStatus = GetSequenceStatusAddr(chip, &chip->mSequence[i]);
168      *pStatus &= 0xff7f; /* wipe "sequence-is-playing" flag */
169   }
170}
171
172static UINT8
173ReadMetaDataByte( struct namcona *chip, int addr )
174{
175   UINT16 data = chip->mpMetaData[addr/2];
176   return (addr&1)?(data&0xff):(data>>8);
177} /* ReadMetaDataByte */
178
179static UINT16
180ReadMetaDataWord( struct namcona *chip, int addr )
181{
182   return ReadMetaDataByte(chip, addr)+ReadMetaDataByte(chip, addr+1)*256;
183} /* ReadMetaDataWord */
184
185static signed char
186ReadPCMSample(struct namcona *chip, int addr, int flag )
187{
188   UINT16 data16 = chip->mpROM[addr/2];
189   int dat = (addr&1)?(data16&0xff):(data16>>8);
190
191   if( flag&0x100 )
192   {
193      if( dat&0x80 )
194      {
195         dat = -(dat&0x7f) - 1;
196      }
197   }
198
199   return dat;
200} /* ReadPCMSample */
201
202static void
203RenderSamples(struct namcona *chip, stream_sample_t **buffer, INT16 *pSource, int length )
204{
205   int i;
206   stream_sample_t * pDest1 = buffer[0];
207   stream_sample_t * pDest2 = buffer[1];
208   for (i = 0; i < length; i++)
209   {
210      INT32 dataL = /* 100 * */ (*pSource++);
211      INT32 dataR = /* 100 * */ (*pSource++);
212      if( dataL > 0x7fff )
213      {
214         dataL =  0x7fff; /* clip */
215      }
216      else if( dataL < -0x8000 )
217      {
218         dataL = -0x8000; /* clip */
219      }
220      if( dataR > 0x7fff )
221      {
222         dataR =  0x7fff; /* clip */
223      }
224      else if( dataR < -0x8000 )
225      {
226         dataR = -0x8000; /* clip */
227      }
228      *pDest1++ = (INT16)dataL; /* stereo left */
229      *pDest2++ = (INT16)dataR; /* stereo right */
230   }
231} /* RenderSamples */
232
233static void
234PushSequenceAddr(struct namcona *chip, struct sequence *pSequence, int addr )
235{
236   if( pSequence->stackSize<MAX_SEQUENCE_RECURSION )
237   {
238      pSequence->stackData[pSequence->stackSize++] = addr;
239   }
240   else
241   {
242      logerror( "sound/namcona.c stack overflow!\n" );
243   }
244} /* PushSequenceAddr */
245
246static void
247PopSequenceAddr(struct namcona *chip, struct sequence *pSequence )
248{
249   if( pSequence->stackSize )
250   {
251      pSequence->addr = pSequence->stackData[--pSequence->stackSize];
252   }
253   else
254   {
255      UINT16 *pStatus = GetSequenceStatusAddr(chip,pSequence);
256      *pStatus &= 0xff7f; /* wipe "sequence-is-playing" flag */
257   }
258} /* PopSequenceAddr */
259
260static void
261HandleSubroutine(struct namcona *chip, struct sequence *pSequence )
262{
263   int addr = ReadMetaDataWord(chip, pSequence->addr );
264   PushSequenceAddr(chip, pSequence, pSequence->addr+2 );
265   pSequence->addr = addr;
266} /* HandleSubroutine */
267
268static void
269HandleRepeat(struct namcona *chip, struct sequence *pSequence )
270{
271   int count = ReadMetaDataByte( chip, pSequence->addr++ );
272   int addr = ReadMetaDataWord(chip, pSequence->addr );
273   if( pSequence->count < count )
274   {
275      pSequence->count++;
276      pSequence->addr = addr;
277   }
278   else
279   {
280      pSequence->count = 0;
281      pSequence->addr += 2;
282   }
283} /* HandleRepeat */
284
285static void
286HandleRepeatOut(struct namcona *chip, struct sequence *pSequence )
287{
288   int count = ReadMetaDataByte( chip, pSequence->addr++ );
289   int addr = ReadMetaDataWord(chip, pSequence->addr );
290   if( pSequence->count2 < count )
291   {
292      pSequence->count2++;
293      pSequence->addr += 2;
294   }
295   else
296   {
297      pSequence->count2 = 0;
298      pSequence->addr = addr;
299   }
300} /* HandleRepeatOut */
301
302static void
303MapArgs(struct namcona *chip, struct sequence *pSequence,
304       int bCommon,
305       void (*callback)( struct namcona *chip, struct sequence *, int chan, UINT8 data ) )
306{
307   UINT8 set = ReadMetaDataByte(chip,pSequence->addr++);
308   UINT8 data = 0;
309   int i;
310   if( bCommon )
311   {
312      data = ReadMetaDataByte( chip, pSequence->addr++ );
313   }
314   for( i=0; i<8; i++ )
315   {
316      if( set&(1<<(7-i)) )
317      {
318         if( !bCommon )
319         {
320            data = ReadMetaDataByte( chip,pSequence->addr++ );
321         }
322         callback( chip, pSequence, i, data );
323      }
324   }
325} /* MapArgs */
326
327static void
328AssignChannel(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
329{
330   if( (pSequence - chip->mSequence) > 1 )
331      data += 16;      /* sound effect */
332
333   if( data<MAX_SEQUENCE_VOICE )
334   {
335      struct voice *pVoice = &chip->mVoice[data];
336      pSequence->channel[chan] = data;
337      pVoice->bActive = 0;
338      pVoice->bank = 0;
339      pVoice->volume = 0x80;
340      pVoice->pan = 0x80;
341      pVoice->dnote = 0;
342      pVoice->detune = 0;
343      pVoice->freqCtrlTableNo = 0;
344      pVoice->freqCtrlSpeed = 0;
345      pVoice->freqCtrlAmp = 0;
346      pVoice->volCtrlTable = 0;
347      pVoice->volCtrlCount = 0;
348      pVoice->panCtrlTable = 0;
349      pVoice->ignoreCount = 0;
350      pVoice->delay = 0;
351      pVoice->portament = 0;
352   }
353} /* AssignChannel */
354
355static void
356IgnoreUnknownOp(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
357{
358} /* IgnoreUnknownOp */
359
360static void
361SelectWave(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
362{
363   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
364   int bank = 0x20000 + pVoice->bank*0x20000;
365   int addr  = ReadMetaDataWord(chip,2)+10*data;
366
367   pVoice->flags    = ReadMetaDataWord(chip,addr+0*2);
368   pVoice->start    = ReadMetaDataWord(chip,addr+1*2)*2+bank;
369   pVoice->end      = ReadMetaDataWord(chip,addr+2*2)*2+bank;
370   pVoice->loop     = ReadMetaDataWord(chip,addr+3*2)*2+bank;
371   pVoice->baseFreq = ReadMetaDataWord(chip,addr+4*2); /* unsure what this is; not currently used */
372
373   pVoice->start <<= FIXED_POINT_SHIFT;
374   pVoice->end   <<= FIXED_POINT_SHIFT;
375   pVoice->loop  <<= FIXED_POINT_SHIFT;
376
377   pVoice->bActive = 0;
378   pVoice->dnote = 0;
379   pVoice->detune = 0;
380} /* SelectWave */
381
382static void
383PlayNote(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
384{
385   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
386   if( data == 0xff )
387   {
388      pVoice->volCtrlCounter = 1;
389   }
390   else
391   {
392      if (pVoice->ignoreCount > 0)
393         pVoice->ignoreCount--;
394      else
395      {
396         pVoice->delayCount = pVoice->delay;
397         pVoice->preNote = pVoice->note;
398         pVoice->note = data<<8;
399         pVoice->bActive |= 4;
400      }
401   }
402} /* PlayNote */
403
404static void
405SelectWaveAndPlayNote(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
406{
407   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
408   int bank = 0x20000 + pVoice->bank*0x20000;
409   int addr = ReadMetaDataWord(chip,4)+10*data;
410   float pbase = (float)SAMPLE_RATE_BASE / (float)chip->mSampleRate;
411   INT32 frequency;
412
413   pVoice->flags    = ReadMetaDataWord(chip,addr+0*2);
414   pVoice->start    = ReadMetaDataWord(chip,addr+3*2)*2+bank;
415   pVoice->end      = ReadMetaDataWord(chip,addr+4*2)*2+bank;
416   pVoice->loop     = pVoice->start;
417
418   pVoice->start <<= FIXED_POINT_SHIFT;
419   pVoice->end   <<= FIXED_POINT_SHIFT;
420   pVoice->loop  <<= FIXED_POINT_SHIFT;
421
422   pVoice->leftVolume  = ReadMetaDataByte(chip,addr+1*2);
423   pVoice->rightVolume = ReadMetaDataByte(chip,addr+1*2+1);
424
425   frequency = ReadMetaDataWord(chip,addr+2*2);
426   pVoice->delta = (long)((float)frequency * pbase);
427   pVoice->delta >>= 16-FIXED_POINT_SHIFT;
428
429   pVoice->bActive = 2;
430   pVoice->pos = pVoice->start;
431} /* SelectWaveAndPlayNote */
432
433static void
434Detune(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
435{
436   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
437   pVoice->detune = data;
438} /* Detune */
439
440
441static void
442DNote(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
443{
444   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
445   pVoice->dnote = data;
446} /* DNote */
447
448static void
449Pan(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
450{
451   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
452   pVoice->pan = data;
453   pVoice->panCtrlSpeed = 0;
454} /* Pan */
455
456static void
457Volume(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
458{
459   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
460   pVoice->volume = pSequence->volume * data / 256;
461} /* Volume */
462
463static void
464FreqCtrlTable(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
465{
466   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
467   pVoice->freqCtrlTableNo = data;
468} /* FreqCtrlTable */
469
470static void
471FreqCtrlSpeed(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
472{
473   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
474   pVoice->freqCtrlSpeed = data;
475} /* FreqCtrlSpeed */
476
477static void
478FreqCtrlAmp(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
479{
480   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
481   pVoice->freqCtrlAmp = data;
482} /* FreqCtrlAmp */
483
484static void
485VolCtrlTable(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
486{
487   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
488   int addr = ReadMetaDataWord(chip,10);
489   addr = ReadMetaDataWord(chip,addr+data*2);
490   pVoice->volCtrlTable = addr;
491} /* VolCtrlTable */
492
493static void
494VolCtrlCount(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
495{
496   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
497   pVoice->volCtrlCount = data;
498} /* VolCtrlCount */
499
500static void
501PanCtrlTable(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
502{
503   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
504   int addr = ReadMetaDataWord(chip,12) + data*4;
505   pVoice->panCtrlTable = addr;
506   pVoice->panCtrlSpeed = ReadMetaDataByte(chip,addr+3);
507   if( pVoice->panCtrlSpeed & 0x80)
508      pVoice->panCtrlSpeed = -(0x100 - pVoice->panCtrlSpeed);
509} /* PanCtrlTable */
510
511static void
512IgnoreCount(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
513{
514   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
515   pVoice->ignoreCount = data;
516} /* IgnoreCount */
517
518static void
519Delay(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
520{
521   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
522   pVoice->delay = data;
523} /* Delay */
524
525static void
526Portament(struct namcona *chip, struct sequence *pSequence, int chan, UINT8 data )
527{
528   struct voice *pVoice = &chip->mVoice[pSequence->channel[chan]];
529   pVoice->portament = (0x100 - data) & 0xff;
530} /* Portament */
531
532static void
533UpdateSequence(struct namcona *chip, struct sequence *pSequence )
534{
535   UINT16 *pStatus = GetSequenceStatusAddr(chip,pSequence);
536   UINT16 data = *pStatus;
537
538   if( data&0x0040 )
539   { /* bit 0x0040 indicates that a sound request was written by the main CPU */
540      int offs = ReadMetaDataWord(chip,0)+(data>>8)*2;
541      memset( pSequence, 0x00, sizeof(struct sequence) );
542      if( pSequence == &chip->mSequence[0] ) Silence(chip); /* hack! */
543      pSequence->addr = ReadMetaDataWord(chip,offs);
544      *pStatus = (data&0xffbf)|0x0080; /* set "sequence-is-playing" flag */
545   }
546   if( data&0x0080 )
547   {
548      if( pSequence == &chip->mSequence[1] )
549      {
550         if( !(*(pStatus-1) & 0x0080) )
551            *pStatus = data&0xff7f;
552      }
553   }
554
555   while( (*pStatus)&0x0080 )
556   {
557      if( pSequence->pause )
558      {
559         pSequence->pause--;
560         return;
561      }
562      else
563      {
564         int code = ReadMetaDataByte(chip,pSequence->addr++);
565         if( code&0x80 )
566         {
567            pSequence->pause = pSequence->tempo*((code&0x7f)+1);
568         }
569         else
570         {
571            int bCommon = (code&0x40);
572            switch( code&0x3f )
573            {
574            case 0x01: /* master volume */
575               pSequence->volume = ReadMetaDataByte(chip,pSequence->addr++);
576               break;
577
578            case 0x02: /* master tempo */
579               pSequence->reg2 = ReadMetaDataByte(chip,pSequence->addr++);
580               break;
581
582            case 0x03: /* tempo */
583               pSequence->tempo = ReadMetaDataByte(chip,pSequence->addr++) * pSequence->reg2;
584               if (pSequence->tempo == 0) pSequence->tempo = 1;
585               break;
586
587            case 0x04:
588               HandleSubroutine(chip, pSequence );
589               break;
590
591            case 0x05: /* end-of-sequence */
592               PopSequenceAddr(chip, pSequence );
593               break;
594
595            case 0x06: /* operand is note index */
596               MapArgs(chip, pSequence, bCommon, PlayNote );
597               pSequence->pause = pSequence->tempo;
598               break;
599
600            case 0x07:
601               MapArgs(chip, pSequence, bCommon, SelectWave );
602               break;
603
604            case 0x08:
605               MapArgs(chip, pSequence, bCommon, Volume );
606               break;
607
608            case 0x09:
609               pSequence->addr = ReadMetaDataWord(chip,pSequence->addr);
610               break;
611
612            case 0x0a:
613               HandleRepeat(chip, pSequence );
614               break;
615
616            case 0x0b:
617               HandleRepeatOut(chip, pSequence );
618               break;
619
620            case 0x0c:
621               MapArgs(chip, pSequence, bCommon, DNote );
622               break;
623
624            case 0x0d:
625               MapArgs(chip, pSequence, bCommon, Detune );
626               break;
627
628            case 0x0e:
629               MapArgs(chip, pSequence, bCommon, FreqCtrlTable );
630               break;
631
632            case 0x0f:
633               MapArgs(chip, pSequence, bCommon, FreqCtrlSpeed );
634               break;
635
636            case 0x12:
637               MapArgs(chip, pSequence, bCommon, FreqCtrlAmp );
638               break;
639
640            case 0x13:
641               MapArgs(chip, pSequence, bCommon, VolCtrlTable );
642               break;
643
644            case 0x11:
645               MapArgs(chip, pSequence, bCommon, VolCtrlCount );
646               break;
647
648            case 0x10:
649               MapArgs(chip, pSequence, bCommon, IgnoreCount );
650               break;
651
652            case 0x14:
653               MapArgs(chip, pSequence, bCommon, Delay );
654               break;
655
656            case 0x16:
657               MapArgs(chip, pSequence, bCommon, Pan );
658               break;
659
660            case 0x17:
661               MapArgs(chip, pSequence, bCommon, PanCtrlTable );
662               break;
663
664            case 0x19: // one loop?
665               if (pSequence->count3 == 0)
666               {
667                  pSequence->addr = ReadMetaDataWord(chip,pSequence->addr);
668                  pSequence->count3++;
669               }
670               else
671               {
672                  pSequence->addr += 2;
673                  pSequence->count3 = 0;
674               }
675               break;
676
677            case 0x1b:
678               MapArgs(chip, pSequence, bCommon, SelectWaveAndPlayNote );
679               pSequence->pause = pSequence->tempo;
680               break;
681
682            case 0x1c: // request sound effect ?
683               pSequence->addr += 2;
684               break;
685
686            case 0x1e:
687               {
688                  int no = ReadMetaDataByte(chip,pSequence->addr++);   /* Sequence No */
689                  int cod = ReadMetaDataByte(chip,pSequence->addr++);
690                  if (no < MAX_SEQUENCE)
691                  {
692                     struct sequence *pSequence2 = &chip->mSequence[no];
693                     UINT16 *pStatus2 = GetSequenceStatusAddr(chip,pSequence2);
694                     int offs = 0x12+cod*2;
695                     *pStatus2 = (cod<<8)|0x0080;
696                     memset( pSequence2, 0x00, sizeof(struct sequence) );
697                     pSequence2->addr = ReadMetaDataWord(chip,offs);
698                  }
699               }
700               break;
701
702            case 0x20:
703               MapArgs(chip, pSequence, bCommon, AssignChannel );
704               break;
705
706            case 0x22:
707               MapArgs(chip, pSequence, bCommon, Portament );
708               break;
709
710            case 0x23:
711               {
712                  UINT8 reg23_0 = ReadMetaDataByte(chip,pSequence->addr++); /* Channel select */
713                  UINT8 reg23_1 = ReadMetaDataByte(chip,pSequence->addr++); /* PCM bank select */
714                  /* reg23_0: 0 = Ch. 0- 3 PCM Bank select
715                                    1 = Ch. 4- 7 PCM Bank select
716                                    2 = Ch. 8-11 PCM Bank select
717                                    3 = Ch.12-15 PCM Bank select
718                        */
719                  if( reg23_0 == 5 ) reg23_0 = 3; /* xday2,bkrtmaq */
720                  if( reg23_0 < 4 )
721                  {
722                     if( (pSequence - chip->mSequence) > 1 )
723                        reg23_0 += 4;      /* sound effect */
724                     chip->mVoice[reg23_0*4 + 0].bank = reg23_1;
725                     chip->mVoice[reg23_0*4 + 1].bank = reg23_1;
726                     chip->mVoice[reg23_0*4 + 2].bank = reg23_1;
727                     chip->mVoice[reg23_0*4 + 3].bank = reg23_1;
728                  }
729               }
730               break;
731
732            case 0x24: // priority ?
733               MapArgs(chip, pSequence, bCommon, IgnoreUnknownOp );
734               break;
735
736            default:
737               //mame_printf_debug( "? 0x%x\n", code&0x3f );
738               *pStatus &= 0xff7f; /* clear "sequence-is-playing" flag */
739               break;
740            }
741         }
742      }
743   }
744} /* UpdateSequence */
745
746static void
747InitFreqCtrl( struct namcona *chip, struct voice *pVoice )
748{
749   if( pVoice->freqCtrlTableNo == 0 )
750   {
751      pVoice->freqCtrlPointer = 0;
752   }
753   else
754   {
755      int addr = ReadMetaDataWord(chip,8);
756      addr = ReadMetaDataWord(chip,addr+pVoice->freqCtrlTableNo*2);
757      pVoice->freqCtrlTable = pVoice->freqCtrlTableNo;
758      pVoice->freqCtrlPointer = addr;
759   }
760   pVoice->freqCtrlCounter = 0;
761   pVoice->freqCtrlFreq = 0;
762}
763
764static void
765UpdateFreqCtrl( struct namcona *chip, struct voice *pVoice )
766{
767   int addr,freq;
768
769   if( !pVoice->freqCtrlPointer ) return;
770
771   pVoice->freqCtrlCounter += pVoice->freqCtrlSpeed;
772   if( pVoice->freqCtrlCounter > 0xff )
773   {
774      pVoice->freqCtrlPointer += pVoice->freqCtrlCounter>>8;
775      pVoice->freqCtrlCounter &= 0xff;
776   }
777
778   switch( ReadMetaDataByte(chip,pVoice->freqCtrlPointer+1) )
779   {
780   case 0xfd:
781      pVoice->freqCtrlTable++;
782   case 0xfe:
783      addr = ReadMetaDataWord(chip,8);
784      addr = ReadMetaDataWord(chip,addr+pVoice->freqCtrlTable*2);
785      pVoice->freqCtrlPointer = addr;
786      break;
787   case 0xff:
788      freq  = ReadMetaDataByte(chip,pVoice->freqCtrlPointer+0) * 0x100;
789      freq -= 100 * 0x100;
790      freq *= pVoice->freqCtrlAmp;
791      freq /= 0x100 * 2;
792      pVoice->freqCtrlFreq = freq;
793      pVoice->freqCtrlPointer = 0;
794      break;
795   default:
796      freq  = ReadMetaDataByte(chip,pVoice->freqCtrlPointer+0) * (0x100 - pVoice->freqCtrlCounter);
797      freq += ReadMetaDataByte(chip,pVoice->freqCtrlPointer+1) *          pVoice->freqCtrlCounter;
798      freq -= 100 * 0x100;
799      freq *= pVoice->freqCtrlAmp;
800      freq /= 0x100 * 2;
801      pVoice->freqCtrlFreq = freq;
802      break;
803   }
804}
805
806static void
807InitVolCtrl( struct namcona *chip, struct voice *pVoice )
808{
809   pVoice->volCtrlPointer = pVoice->volCtrlTable;
810   pVoice->volCtrlCounter = pVoice->volCtrlCount;
811   if( pVoice->volCtrlCounter > 0 ) pVoice->volCtrlCounter++;
812   if( pVoice->volCtrlPointer )
813   {
814      pVoice->volCtrlSpeed  = VolCtrlSpeedTable[ReadMetaDataByte(chip,pVoice->volCtrlPointer) & 0x7f];
815      pVoice->volCtrlVolEnd = ReadMetaDataByte(chip,pVoice->volCtrlPointer+1)<<8;
816      pVoice->volCtrlPointer += 2;
817      pVoice->volCtrlVol = 0;
818   }
819   else
820   {
821      pVoice->volCtrlVol = 0xffff;
822   }
823}
824
825static void
826UpdateVolCtrl( struct namcona *chip, struct voice *pVoice )
827{
828   if( !pVoice->volCtrlPointer ) return;
829
830   if( pVoice->volCtrlCounter == 1 )
831   {
832      pVoice->volCtrlCounter = 0;
833
834      while( pVoice->volCtrlPointer )
835      {
836         if( ReadMetaDataByte(chip,pVoice->volCtrlPointer) == 0x00 )
837         {
838            if( ReadMetaDataByte(chip,pVoice->volCtrlPointer+1) == 0xff )
839            {
840               pVoice->volCtrlPointer = 0;
841               pVoice->bActive &= ~1;
842            }
843            else
844            {
845               pVoice->volCtrlPointer += 2;
846               pVoice->volCtrlSpeed  = VolCtrlSpeedTable[ReadMetaDataByte(chip,pVoice->volCtrlPointer) & 0x7f];
847               pVoice->volCtrlVolEnd = ReadMetaDataByte(chip,pVoice->volCtrlPointer+1)<<8;
848               pVoice->volCtrlPointer += 2;
849            }
850            break;
851         }
852         pVoice->volCtrlPointer += 2;
853      }
854   }
855   else
856   {
857      int next = 0;
858
859      if( pVoice->volCtrlCounter > 0 )
860         pVoice->volCtrlCounter--;
861
862      if( pVoice->volCtrlVol < pVoice->volCtrlVolEnd )
863      {
864         pVoice->volCtrlVol += pVoice->volCtrlSpeed;
865         if( pVoice->volCtrlVol >= pVoice->volCtrlVolEnd )
866         {
867            pVoice->volCtrlVol = pVoice->volCtrlVolEnd;
868            next = 1;
869         }
870      }
871      else
872      {
873         pVoice->volCtrlVol -= pVoice->volCtrlSpeed;
874         if( pVoice->volCtrlVol <= pVoice->volCtrlVolEnd )
875         {
876            pVoice->volCtrlVol = pVoice->volCtrlVolEnd;
877            next = 1;
878         }
879      }
880
881      if( next )
882      {
883         UINT8 val1, val2;
884
885         val1 = ReadMetaDataByte(chip,pVoice->volCtrlPointer+0);
886         val2 = ReadMetaDataByte(chip,pVoice->volCtrlPointer+1);
887
888         if( val1 == 0x00 && val2 > 0x80 )
889         {
890            pVoice->volCtrlPointer = 0;
891            pVoice->bActive &= ~1;
892         }
893         else if( val1 != 0x00 || val2 != 0x80 )
894         {
895            if( val1 == 0x00 )
896               pVoice->volCtrlPointer = pVoice->volCtrlTable + val2;
897            pVoice->volCtrlSpeed  = VolCtrlSpeedTable[ReadMetaDataByte(chip,pVoice->volCtrlPointer) & 0x7f];
898            pVoice->volCtrlVolEnd = ReadMetaDataByte(chip,pVoice->volCtrlPointer+1)<<8;
899            pVoice->volCtrlPointer += 2;
900         }
901      }
902   }
903}
904
905
906static void
907InitPanCtrl( struct namcona *chip, struct voice *pVoice )
908{
909   if( pVoice->panCtrlTable != 0 && pVoice->panCtrlSpeed != 0)
910   {
911      pVoice->panCtrlEnable = 1;
912      pVoice->panCtrlCounter = ReadMetaDataByte(chip,pVoice->panCtrlTable);
913      if( pVoice->panCtrlCounter != 0xFE )
914         pVoice->pan = ReadMetaDataByte(chip,pVoice->panCtrlTable+1);
915   }
916   else
917   {
918      pVoice->panCtrlEnable = 0;
919   }
920}
921
922static void
923UpdatePanCtrl( struct namcona *chip, struct voice *pVoice )
924{
925   if( pVoice->panCtrlEnable )
926   {
927      if( pVoice->panCtrlCounter == 0 )
928      {
929         UINT8 pan_2 = ReadMetaDataByte(chip,pVoice->panCtrlTable+2);
930         UINT8 pan_3 = ReadMetaDataByte(chip,pVoice->panCtrlTable+3);
931         if( !(pan_3&0x80) )
932         {
933            pVoice->pan += pan_3;
934            if( pVoice->pan > 0xff || pVoice->pan >= pan_2)
935            {
936               pVoice->pan = pan_2;
937               pVoice->panCtrlEnable = 0;
938            }
939         }
940         else
941         {
942            pVoice->pan -= 0x100 - pan_3;
943            if( pVoice->pan < 0 || pVoice->pan <= pan_2)
944            {
945               pVoice->pan = pan_2;
946               pVoice->panCtrlEnable = 0;
947            }
948         }
949      }
950      else if( pVoice->panCtrlCounter < 0xFE )
951      {
952         pVoice->panCtrlCounter--;
953      }
954      else
955      {
956         if( pVoice->panCtrlSpeed >= 0 )
957         {
958            pVoice->pan += pVoice->panCtrlSpeed;
959            if( pVoice->pan > 0xff )
960            {
961               pVoice->pan = 0xff;
962               pVoice->panCtrlSpeed = -pVoice->panCtrlSpeed;
963            }
964         }
965         else
966         {
967            pVoice->pan += pVoice->panCtrlSpeed;
968            if( pVoice->pan < 0 )
969            {
970               pVoice->pan = 0;
971               pVoice->panCtrlSpeed = -pVoice->panCtrlSpeed;
972            }
973         }
974      }
975   }
976}
977
978static void
979InitPortament( struct namcona *chip, struct voice *pVoice )
980{
981   pVoice->portamentSpeed = pVoice->portament;
982}
983
984static void
985UpdatePortament( struct namcona *chip, struct voice *pVoice )
986{
987   if( !pVoice->portamentSpeed )
988   {
989      pVoice->portamentNote = pVoice->note;
990   }
991   else
992   {
993      int note;
994      note = pVoice->note - pVoice->preNote;
995      if( note >= 0 )
996      {
997         note = (note/256+1) * pVoice->portamentSpeed / 2;
998         pVoice->portamentNote += note;
999         if( pVoice->portamentNote > pVoice->note )
1000         {
1001            pVoice->portamentNote = pVoice->note;
1002            pVoice->portamentSpeed = 0;
1003         }
1004      }
1005      else
1006      {
1007         note = (-note/256+1) * pVoice->portamentSpeed / 2;
1008         pVoice->portamentNote -= note;
1009         if( pVoice->portamentNote < pVoice->note )
1010         {
1011            pVoice->portamentNote = pVoice->note;
1012            pVoice->portamentSpeed = 0;
1013         }
1014      }
1015   }
1016}
1017
1018static void
1019StartPlayNote( struct namcona *chip, struct voice *pVoice )
1020{
1021   if( pVoice->bActive & 4 )
1022   {
1023      if( pVoice->delayCount == 0)
1024      {
1025         pVoice->bActive &= ~4;
1026         pVoice->bActive |= 1;
1027         pVoice->pos = pVoice->start;
1028         InitFreqCtrl( chip, pVoice );
1029         InitVolCtrl( chip, pVoice );
1030         InitPanCtrl( chip, pVoice );
1031         InitPortament( chip, pVoice );
1032      }
1033      else
1034         pVoice->delayCount--;
1035   }
1036}
1037
1038static void
1039UpdatePlayNote( struct namcona *chip, struct voice *pVoice )
1040{
1041   int vol;
1042   UINT16 Note = pVoice->portamentNote + (pVoice->dnote<<8) + pVoice->detune + pVoice->baseFreq;
1043   Note += pVoice->freqCtrlFreq;
1044   Note &= 0x7fff;
1045   pVoice->delta = chip->mpPitchTable[Note>>8];
1046   pVoice->delta += (chip->mpPitchTable[(Note>>8)+1]-pVoice->delta) * (Note&0xff) / 256;
1047
1048   vol = (pVoice->volCtrlVol>>8) * pVoice->volume / 256;
1049   pVoice->leftVolume  = (0x100-pVoice->pan) * vol / 256;
1050   pVoice->rightVolume = pVoice->pan * vol / 256;
1051}
1052
1053static void
1054UpdateStatus( struct namcona *chip, struct voice *pVoice )
1055{
1056   StartPlayNote( chip, pVoice );
1057   if( pVoice->bActive & 1 )
1058   {
1059      UpdateFreqCtrl( chip, pVoice );
1060      UpdateVolCtrl( chip, pVoice );
1061      UpdatePanCtrl( chip, pVoice );
1062      UpdatePortament( chip, pVoice );
1063      UpdatePlayNote( chip, pVoice );
1064   }
1065}
1066
1067static void
1068UpdateSound( void *param, stream_sample_t **inputs, stream_sample_t **buffer, int length )
1069{
1070   struct namcona *chip = param;
1071   int i;
1072
1073   for( i=0; i<MAX_SEQUENCE; i++ )
1074      UpdateSequence(chip, &chip->mSequence[i] );
1075   for( i=0; i<MAX_SEQUENCE_VOICE; i++ )
1076      UpdateStatus(chip, &chip->mVoice[i] );
1077   for( i=0; i<MAX_SEQUENCE; i++ )
1078      UpdateSequence(chip, &chip->mSequence[i] );
1079   for( i=0; i<MAX_SEQUENCE_VOICE; i++ )
1080      UpdateStatus(chip, &chip->mVoice[i] );
1081
1082   if( length>chip->mSampleRate ) length = chip->mSampleRate;
1083   memset(chip->mpMixerBuffer, 0, length * sizeof(INT16) * 2);
1084   for( i=0;i<MAX_VOICE;i++ )
1085   {
1086      struct voice *pVoice;
1087      if( chip->mVoice[i+16].bActive & 3 )
1088         pVoice = &chip->mVoice[i+16];   //sound effect is high priority
1089      else
1090         pVoice = &chip->mVoice[i];
1091
1092      if( (pVoice->bActive & 3) && pVoice->delta )
1093      {
1094         INT32 delta  = pVoice->delta;
1095         INT32 end    = pVoice->end;
1096         INT32 pos    = pVoice->pos;
1097         INT32 lvol   = pVoice->leftVolume;
1098         INT32 rvol   = pVoice->rightVolume;
1099         INT16 *pDest = chip->mpMixerBuffer;
1100         INT16 dat;
1101         int j;
1102         for( j=0; j<length; j++ )
1103         {
1104            if( pos >= end )
1105            {
1106               if( pVoice->flags&0x1000 )
1107               {
1108                  pos = pos - end + pVoice->loop;
1109               }
1110               else
1111               {
1112                  pVoice->bActive &= ~3;
1113                  break;
1114               }
1115            }
1116            dat = ReadPCMSample(chip,pos>>FIXED_POINT_SHIFT, pVoice->flags)*32;
1117            *pDest++ += dat*lvol/256;
1118            *pDest++ += dat*rvol/256;
1119            pos += delta;
1120         }
1121         pVoice->pos = pos;
1122      }
1123   }
1124   RenderSamples(chip, buffer, chip->mpMixerBuffer, length );
1125} /* UpdateSound */
1126
1127static void *namcona_start(const char *tag, int sndindex, int clock, const void *config)
1128{
1129   const namcona_interface *intf = config;
1130   struct namcona *chip;
1131   chip = auto_malloc(sizeof(*chip));
1132   memset(chip, 0, sizeof(*chip));
1133   chip->mSampleRate = clock;
1134   chip->mStream = stream_create(0, 2, chip->mSampleRate, chip, UpdateSound);
1135   chip->mpROM = (UINT16 *)intf->memory_base;
1136   chip->mpMetaData = chip->mpROM+intf->metadata_offset;
1137
1138   memset( chip->mVoice, 0x00, sizeof(chip->mVoice) );
1139   memset( chip->mSequence, 0x00, sizeof(chip->mSequence) );
1140
1141   chip->mpMixerBuffer = auto_malloc( sizeof(INT16)*chip->mSampleRate*2 );
1142   chip->mpPitchTable = auto_malloc( sizeof(INT32)*0xff );
1143      {
1144         int i;
1145         for( i=0; i<0xff; i++ )
1146         {
1147            int data = i;
1148            double freq = freq = (1<<FIXED_POINT_SHIFT)/4;
1149            while( data>0x3a )
1150            {
1151               data--;
1152               freq *= kTwelfthRootTwo;
1153            }
1154            while( data<0x3a )
1155            {
1156               data++;
1157               freq /= kTwelfthRootTwo;
1158            }
1159            chip->mpPitchTable[i] = (INT32)freq;
1160         }
1161      }
1162   return chip;
1163} /* NAMCONA_sh_start */
1164
1165#if 0
1166static void
1167DumpSampleTable( FILE *f, struct namcona *chip, int table, unsigned char *special )
1168{
1169   int iStart = ReadMetaDataWord(chip,table);
1170   int i=iStart;
1171   fprintf( f, "\nsample table:\n" );
1172   while( i<0x10000 )
1173   {
1174      fprintf( f, "%04x(%02x): %04x %04x %04x %04x %04x (len=%d)\n",
1175         i, (i-iStart)/10,
1176         ReadMetaDataWord(chip,i+0*2), // flags
1177         ReadMetaDataWord(chip,i+1*2), // start
1178         ReadMetaDataWord(chip,i+2*2), // end
1179         ReadMetaDataWord(chip,i+3*2), // loop
1180         ReadMetaDataWord(chip,i+4*2), // freq
1181         ReadMetaDataWord(chip,i+2*2)-ReadMetaDataWord(chip,i+1*2) );
1182      i+=5*2;
1183      if( special[i] || special[i+1] ) break;
1184   }
1185   fprintf( f, "\n" );
1186}
1187
1188static void
1189DumpBytes( FILE *f, struct namcona *chip, int addr, unsigned char *special )
1190{
1191   fprintf( f, "%04x:", addr );
1192   while( addr<0x10000 )
1193   {
1194      fprintf( f, " %02x", ReadMetaDataByte(chip,addr) );
1195      addr++;
1196      if( (addr&0xf)==0 ) fprintf( f, "\n%04x;", addr );
1197      if( special[addr] ) break;
1198   }
1199   fprintf( f, "\n" );
1200}
1201
1202static void
1203DumpUnkTable( FILE *f, struct namcona *chip, int table, unsigned char *special )
1204{
1205   int iStart = ReadMetaDataWord(chip,table);
1206   int iFinish = ReadMetaDataWord(chip,iStart);
1207   int i,addr;
1208
1209   if( iFinish<iStart )
1210   { /* hack for CosmoGang */
1211      iFinish = ReadMetaDataWord(chip,iStart+2);
1212   }
1213
1214   fprintf( f, "\nunk table; %d entries:\n", (iFinish-iStart)/2 );
1215   fprintf( f, "%04x:", iStart );
1216
1217
1218   for( i=iStart; i<iFinish; i+=2 )
1219   {
1220      addr = ReadMetaDataWord(chip,i);
1221      fprintf( f, " %04x", addr );
1222      special[addr] = 1;
1223   }
1224   fprintf( f,"\n" );
1225   for( i=iStart; i<iFinish; i+=2 )
1226   {
1227      addr = ReadMetaDataWord(chip,i);
1228      fprintf( f, "%04x:", addr );
1229      for(;;)
1230      {
1231         fprintf( f, " %02x", ReadMetaDataByte(chip,addr) );
1232         addr++;
1233         if( addr>=0x10000 || special[addr] ) break;
1234      }
1235      fprintf( f, "\n" );
1236   }
1237   fprintf( f, "\n" );
1238}
1239#endif
1240
1241static void
1242namcona_stop( void *chip )
1243{
1244   #if 0
1245   FILE *f = fopen("snd.txt","w");
1246   if( f )
1247   {
1248      unsigned char *special = malloc(0x10000);
1249      if( special )
1250      {
1251         int i,addr, table;
1252         memset( special, 0x00, 0x10000 );
1253         for( i=0; i<0x12; i+=2 )
1254         {
1255            addr = ReadMetaDataWord(chip,i);
1256            if( i ) special[addr] = 1;
1257            fprintf( f, "%04x: %04x\n", i, addr );
1258         }
1259         table = 0x12;
1260         i = table;
1261         while( i<0x10000 )
1262         {
1263            addr = ReadMetaDataWord(chip,i);
1264            special[addr] = 1;
1265            i+=2;
1266            if( special[i] ) break;
1267         }
1268         DumpSampleTable( f, chip, 0x0002, special );
1269         DumpSampleTable( f, chip, 0x0004, special );
1270         /* 0x0006 is unused */
1271         DumpUnkTable( f, chip, 0x0008, special );
1272         DumpUnkTable( f, chip, 0x000a, special );
1273         fprintf( f, "\nunknown chunk:\n" );
1274         DumpBytes(f, chip, ReadMetaDataWord(chip,0x0c), special );
1275         DumpSampleTable( f, chip, 0x000e, special );
1276         fprintf( f, "\nSong Table:\n" );
1277         i = 0x12;
1278         while( i<0x10000 )
1279         {
1280            addr = ReadMetaDataWord(chip,i);
1281            fprintf( f, "[%02x] ", (i-0x12)/2 );
1282            DumpBytes( f,chip,addr,special );
1283            i+=2;
1284            if( special[i] ) break;
1285         }
1286         free( special );
1287      }
1288      fclose( f );
1289   }
1290   #endif
1291} /* NAMCONA_sh_stop */
1292
1293
1294
1295
1296/**************************************************************************
1297 * Generic get_info
1298 **************************************************************************/
1299
1300static void namcona_set_info(void *token, UINT32 state, sndinfo *info)
1301{
1302   switch (state)
1303   {
1304      /* no parameters to set */
1305   }
1306}
1307
1308
1309void namcona_get_info(void *token, UINT32 state, sndinfo *info)
1310{
1311   switch (state)
1312   {
1313      /* --- the following bits of info are returned as 64-bit signed integers --- */
1314
1315      /* --- the following bits of info are returned as pointers to data or functions --- */
1316      case SNDINFO_PTR_SET_INFO:                  info->set_info = namcona_set_info;      break;
1317      case SNDINFO_PTR_START:                     info->start = namcona_start;         break;
1318      case SNDINFO_PTR_STOP:                     info->stop = namcona_stop;            break;
1319      case SNDINFO_PTR_RESET:                     /* Nothing */                     break;
1320
1321      /* --- the following bits of info are returned as NULL-terminated strings --- */
1322      case SNDINFO_STR_NAME:                     info->s = "Namco NA";               break;
1323      case SNDINFO_STR_CORE_FAMILY:               info->s = "Namco custom";            break;
1324      case SNDINFO_STR_CORE_VERSION:               info->s = "1.0";                  break;
1325      case SNDINFO_STR_CORE_FILE:                  info->s = __FILE__;                  break;
1326      case SNDINFO_STR_CORE_CREDITS:               info->s = "Copyright Nicola Salmoria and the MAME Team"; break;
1327   }
1328}
1329
src/emu/sound/namcona.h
r3367r3368
1/* namcona1.h */
2
3#pragma once
4
5#ifndef __NAMCONA_H__
6#define __NAMCONA_H__
7
8typedef struct _namcona_interface namcona_interface;
9struct _namcona_interface
10{
11    void *memory_base;
12    int metadata_offset;
13};
14
15#endif /* __NAMCONA_H__ */

Previous 15994 Revisions Next


© 1998-2018 The MESS Team