home *** CD-ROM | disk | FTP | other *** search
/ Shareware 1 2 the Maxx / sw_1.zip / sw_1 / PROGRAM / SBDOS10.ZIP / SB_DRIVE.C < prev    next >
Text File  |  1992-06-25  |  41KB  |  1,353 lines

  1. /*======================================================================
  2.  
  3.    Device driver for the Creative Labs Sound Blaster card.
  4.  
  5.    [ This file is part of the SBMSDOS v1.0 distibution ]
  6.  
  7.    Michael Fulbright (msf@as.arizona.edu)
  8.  
  9.    This file was originally distributed by the fellow below, I'm
  10.    just borrowing it.
  11.  
  12.    =====================================================================
  13.    ORIGINAL HEADER FOLLOWS (msf)
  14.    =====================================================================
  15.  
  16.    [ This file is a part of SBlast-BSD-1.4 ]
  17.  
  18.    Steve Haehnichen <shaehnic@ucsd.edu>
  19.  
  20.    $Id: sb_driver.c,v 1.29 1992/06/13 01:46:43 steve Exp steve $
  21.  
  22.    Copyright (C) 1992 Steve Haehnichen.
  23.  
  24.    This program is free software; you can redistribute it and/or modify
  25.    it under the terms of the GNU General Public License as published by
  26.    the Free Software Foundation; either version 1, or (at your option)
  27.    any later version.
  28.  
  29.    This program is distributed in the hope that it will be useful,
  30.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  31.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  32.    GNU General Public License for more details.
  33.  
  34.    You should have received a copy of the GNU General Public License
  35.    along with this program; if not, write to the Free Software
  36.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  37.  
  38.  * $Log: sb_driver.c,v $
  39.  * Revision 1.29  1992/06/13  01:46:43  steve
  40.  * Released in SBlast-BSD-1.4
  41.  
  42. ======================================================================*/
  43. /* MSF - Following not needed for MSDOS
  44. #include <sys/user.h>
  45. #include <sys/file.h>
  46. */
  47.  
  48. /* MSF - following needed in general */
  49. #include <stdio.h>
  50. #include <stdlib.h>
  51.  
  52. /* MSF - following needed for MSC specific calls */
  53. #include <dos.h>
  54. #include <bios.h>
  55.  
  56. #include "sblast.h"             /* User-level structures and defs */
  57. #include "sb_regs.h"        /* Register and command values */
  58.  
  59. /*
  60.  * Defining DEBUG will print out lots of useful kernel activity
  61.  * information.  If there are problems, it's the first thing you
  62.  * should do.  You can also define FULL_DEBUG for more info than
  63.  * you probably want.  (If you consider any DEBUG useless, just
  64.  * turn it into a FULL_DEBUG.)
  65.  */
  66. /* #define DEBUG */
  67. /* #define FULL_DEBUG */
  68. #if defined (FULL_DEBUG) && !defined (DEBUG)
  69. #  define DEBUG
  70. #endif
  71.  
  72. /*
  73.  * Here's the debugging macro I use here and there, so I can turn
  74.  * them all on or off in one place.
  75.  */
  76. #ifdef DEBUG
  77. #  define DPRINTF(x)    printf x
  78. #else
  79. #  define DPRINTF(x)
  80. #endif
  81.  
  82. /*
  83.  * This is the highest DSP speed that will use "Low-Speed" mode.
  84.  * Anything greater than this will use the "High-Speed" mode instead.
  85.  */
  86. #define        MAX_LOW_SPEED    22222
  87.  
  88. /*
  89.  * This is the speed the DSP will start at when you reboot the system.
  90.  * If I can read the speed registers, then maybe I should just use
  91.  * the current card setting.  Does it matter?
  92.  * (43478 is the closest we can get to 44 KHz)
  93.  */
  94. #define         INITIAL_DSP_SPEED       8000
  95.  
  96. /*
  97.  * Define this if you consider ADC overruns to be an error, and
  98.  * want to abort the read() call.  If you are making real recordings,
  99.  * this is usually the case, or you will have gaps in the sound.
  100.  * (This shouldn't happen.  Most apps can keep up with 45K/sec.)
  101.  * For real-time use, overruns should be ignored.
  102.  * This looks like an ioctl-toggle candidate to me. 
  103.  */
  104. #define     ERROR_ON_OVERRUN
  105.  
  106. #define FALSE 0
  107. #define TRUE 1
  108.  
  109. #define GOOD 1
  110. #define FAIL 0
  111. #define ON   1
  112. #define OFF  0
  113.  
  114.  
  115. /* Number of "cycles" in one second.  Shouldn't this be somewhere else? */
  116. #define HZ         100
  117.  
  118. #define TIMEOUT        (10 * HZ) /* FM interrupt patience in clock ticks */
  119.  
  120. /* Semaphore return codes.  This tells the reason for the wakeup(). */
  121. #define WOKEN_BY_INTERRUPT      1
  122. #define WOKEN_BY_TIMEOUT        2
  123.  
  124. #define DSP_LOOP_MAX 10000
  125.  
  126. #define DSP_UNIT 0
  127.  
  128. enum { PLAY, RECORD };        /* DSP sampling directions */
  129.  
  130. /*
  131.  * NOTE - MSF - Well, I cant afford OS/2 yet, so I'm stuck with
  132.  *              wonderful 64k segments in MSC 5.1. Comment below
  133.  *              holds, except I allocate 2 buffers in a 32k chunk.
  134.  *              To be sure things will work DO NOT CHOOSE DSP_BUF_SIZE
  135.  *              to be larger than 1/3 sizeof(memory_chunk)!.
  136.  *
  137.  * ORIGINAL COMMENT FOLLOWS (msf)
  138.  *
  139.  * This is the DSP memory buffer size.  Choose wisely. :-)
  140.  * I started with 21K buffers, and then later changed to 64K buffers.
  141.  * This hogs more kernel memory, but gives fewer Pops and
  142.  * needs servicing less often.  Adjust to taste.
  143.  * Note that it must be an EVEN number if you want stereo to work.
  144.  * (See dsp_find_buffers() for a better explanation
  145.  * Note that the same amount of memory (192K) is hogged, regardless of
  146.  * the buffer size you choose.  This makes it easier to allocate page-safe
  147.  * buffers, but should probably be changed to attempt to pack more into
  148.  * one 64K page.  Be really sure you understand what you are doing if
  149.  * you change the size of memory_chunk[].
  150.  * 64K is the biggest DSP_BUF_SIZE you can have.
  151.  * Smaller buffer sizes make aborts and small reads more responsive.
  152.  * For real-time stuff, perhaps ~10K would be better.
  153.  */
  154. #define DSP_BUF_SIZE            (10000)
  155. static char memory_chunk[32 * 1024]; /* Be careful!  See above */
  156.  
  157. /* This structure will be instantiated as a single global holder
  158.    for all DSP-related variables and flags. */
  159. /* MSF - added speaker_on flag to tell if speaker on or off */
  160.  
  161. struct sb_dsp_type
  162. {
  163.   unsigned int  speed;          /* DSP sampling rate */
  164.   int    timeout;        /* Timeout for one DSP buffer */
  165.   BYTE    compression;        /* Current DAC decompression mode */
  166.   FLAG    hispeed;        /* 1 = High Speed DSP mode, 0 = low speed */
  167.   FLAG  in_stereo;        /* 1 = currently in stereo, 0 = mono */
  168.   BYTE    start_command;        /* current DSP start command */
  169.   int    error;            /* Current error status on read/write */
  170.   int    semaphore;        /* Silly place-holder int for dsp_dma_start */
  171.   void  (*cont_xfer)(void);    /* Function to call to continue a DMA xfer */
  172.   char    *buf[2];        /* Two pointers to mono-page buffers */
  173.   long  phys_buf[2];            /* Physical addresses for dsp buffers */
  174.   FLAG    full[2];        /* True when that buffer is full */
  175.   int    used[2];        /* Buffer bytes used by read/write */
  176.   BYTE  active;            /* The buffer currently engaged in DMA */
  177.   BYTE  hi;            /* The buffer being filled/emptied by user */
  178.   FLAG    first_block;        /* True for the first DAC block */
  179.   FLAG  dont_block;             /* FNDELAY flag sets this, clear otherwise */
  180.   FLAG  speaker_on;             /* added by MSF - TRUE - voice on, else off */
  181. };
  182. static struct sb_dsp_type dsp;    /* 'dsp' structure used everywhere */
  183.  
  184. #define NUM_UNITS 1
  185.  
  186. /* This will be used as a global holder for the current Sound Blaster
  187.    general status values. */
  188. struct sb_status_type
  189. {
  190.   FLAG    dsp_in_use;        /* DSP or MIDI open for reading or writing */
  191.   FLAG  fm_in_use;        /* FM open for ioctls */
  192.   FLAG  cms_in_use;        /* CMS open for ioctls */
  193.   
  194.   FLAG  alive;                  /* Card present? */
  195.   unsigned int addr;            /* Sound Blaster card address */
  196.   unsigned int irq;             /* MSF-added this */
  197.   int  *wake[NUM_UNITS];    /* What to wakeup on interrupt */
  198. };
  199. static struct sb_status_type status; /* Global current status */
  200.  
  201.  
  202. /*
  203.  * Forward declarations galore!
  204.  */
  205. int sb_probe (struct sb_conf *dev);
  206. int sb_attach (struct sb_conf *dev);
  207. void sb_unattach (void);
  208. void sb_sendb (unsigned select_addr, BYTE reg,
  209.               unsigned data_addr, BYTE value);
  210. int dsp_reset (void);
  211. int dsp_open (void);
  212. int dsp_close (int flags);
  213. unsigned int dsp_set_speed (unsigned int *speed);
  214. int dsp_command (BYTE val);
  215. int dsp_set_voice (int on);
  216.  int dsp_flush_dac (void);
  217.  int dsp_set_compression (int mode);
  218.  int dsp_set_stereo (FLAG on);
  219.  int dsp_write (BYTE far *ptr, int len);
  220.  int dsp_read (BYTE far *ptr, int len);
  221.  void dsp_find_buffers (void);
  222.  void dsp_dma_start (int dir);
  223.  void dsp_next_write (void);
  224.  void dsp_next_read (void);
  225.  void mixer_send (BYTE reg, BYTE val);
  226.  BYTE mixer_read_reg (BYTE reg);
  227.  int mixer_reset (void);
  228.  int mixer_set_levels (struct sb_mixer_levels *l);
  229.  int mixer_set_params (struct sb_mixer_params *p);
  230.  int mixer_get_levels (struct sb_mixer_levels *l);
  231.  int mixer_get_params (struct sb_mixer_params *params);
  232.  
  233.  
  234.  
  235. /* added by msf */
  236. /* old_irqptr holds the old vector for the SB IRQ while we use it here.
  237.  *  The IRQ vector is restored to this value when the program terminates */
  238. void (_CDECL interrupt far * _CDECL old_irqptr)();
  239.  
  240. /* this is how on declares a function to be an interrupt handler under
  241.  *  MSC 5.1.   I know Borland compilers have their own way of handling this */
  242. void cdecl interrupt far sb_intr (void);
  243. void outb( int, int );
  244.  
  245. /* MSF - following implements my own 'sleep' functions.
  246.  * time_const contains the number of loops/s a for loop can do */
  247. unsigned long time_const;
  248. void init_timers(void);
  249.  
  250. /* 
  251.  * Probing sets dev->dev_alive, status.alive, and returns 1 if the
  252.  * card is detected.  Note that we are not using the "official" Adlib
  253.  * of checking for the presence of the card because it's tacky and
  254.  * takes too much mucking about.  We just attempt to reset the DSP and
  255.  * assume that a DSP-READY signal means the card is there.  If you
  256.  * have another card that fools this probe, I'd really like to hear
  257.  * about it. :-) Future versions may query the DSP version number
  258.  * instead.
  259.  */
  260. int
  261. sb_probe (struct sb_conf *dev)
  262. {
  263. #ifdef FULL_DEBUG
  264.   printf ("sb: sb_probe() called.\n");
  265.   printf ("Dev.addr = %d, dev.irq= %d \n",dev->addr, dev->irq);
  266. #endif
  267.  
  268.   status.addr = (unsigned int) dev->addr;
  269.  
  270.   if (dsp_reset () == GOOD)
  271.     status.alive = 1;
  272.   else
  273.     {
  274.       status.alive = 0;
  275.       printf ("sb: Sound Blaster Not found!  Driver not installed.\n");
  276.     }
  277.   return (status.alive);
  278. }
  279.  
  280. /* This is called by the kernel if probe() is successful. */
  281. int
  282. sb_attach (struct sb_conf *dev)
  283. {
  284.   int i;
  285.   unsigned char im, tm;
  286.   unsigned long pp;
  287.  
  288.   /* MSF - added irq field to status */
  289.   status.addr = (unsigned int) dev->addr;
  290.   status.irq =  (unsigned int) dev->irq;
  291.   status.fm_in_use = 0;
  292.   status.dsp_in_use = 0;
  293.   status.addr = (unsigned int) dev->addr;
  294.   status.irq =  (unsigned int) dev->irq;
  295.  
  296.   DPRINTF(("status.addr,status.irq= %x %x\n",status.addr,status.irq));
  297.   DPRINTF(("dev.addr,dev.irq= %x %x\n",dev->addr,dev->irq));
  298.  
  299.   dsp_find_buffers();
  300.   for (i = 0; i < NUM_UNITS; i++)
  301.     status.wake[i] = NULL;
  302.  
  303.   /*
  304.    * These are default startup settings.
  305.    * I'm wondering if I should just leave the card in the same
  306.    * speed/stereo state that it is in.  I decided to leave the mixer
  307.    * alone, and like that better.  Ideas?
  308.    */
  309.   dsp.compression = PCM_8;
  310.   dsp.speed = INITIAL_DSP_SPEED;
  311.   dsp_set_stereo (FALSE);
  312.  
  313.   /* MSF - added this to set up some more things */
  314.   dsp_open();
  315.  
  316.   /* MSF - calculate delay time constants for 'sleep' simulator */
  317.   init_timers();
  318.  
  319.   /* MSF - added following to grab SB IRQ.
  320.    * If some of code looks familiar to you, thanks. I grabbed it off of
  321.    * blaster@porter.geo.brown.edu and cant find name of poster. */
  322.  
  323.   /* now turn on the interrupt */
  324.   /* Enable interrupts on PIC */
  325.   im = inp(0x21);
  326.   tm = ~(1 << dev->irq);
  327.   outb(0x21,im & tm);
  328.   _enable();
  329.   outb(0x20,0x20);
  330.   DPRINTF(("Interrupt mask register = %d\n",im));
  331.   DPRINTF(("Setup IRQ %d with mask %d\n",dev->irq, tm));
  332.  
  333.   /* Set up DSP interrupt */
  334.   pp = (unsigned long) _dos_getvect(8+dev->irq);
  335.   DPRINTF(("IRQ 7 was now %lu \n",pp));
  336.   /* grab old vector and store */
  337.   old_irqptr = _dos_getvect(8+dev->irq);
  338.   _dos_setvect(8+dev->irq, sb_intr);
  339.   _enable();
  340.  
  341.   DPRINTF (("sb: Sound Blaster installed. (Port 0x%X, IRQ %d, DMA %d)\n",
  342.       status.addr, dev->irq, SB_DMA_CHAN));
  343.  
  344.   /* MSF - set things up so if program exits it will call sb_unattach */
  345.   i=atexit( sb_unattach );
  346.   if (i!=0)
  347.      printf("Error calling atexit\n");
  348.  
  349.  
  350.   return (GOOD);
  351. }
  352.  
  353.  
  354. /* MSF - This should be called when done, resets interrupts and stuff
  355.  *       Machine can act unpredictably otherwise.                     */
  356. void
  357. sb_unattach (void)
  358. {
  359.    unsigned char  tm;
  360.  
  361.  
  362.   DPRINTF(("In sb_unattach\n"));
  363.  
  364.   /* see if any DMA is going on */
  365.   if (dsp.cont_xfer != NULL)
  366.    {
  367.       printf("Waiting for DMA to cease.\n");
  368.       tm=wait_for_intr(dsp.timeout);
  369.       if (tm==FAIL) printf("Couldnt get interrupt, unattaching anyway!\n");
  370.    }
  371.  
  372.   /* Return DSP interrupt */
  373.   if ( old_irqptr != NULL )
  374.    {
  375.      DPRINTF(("Resetting vector back to original\n"));
  376.     _dos_setvect(8+status.irq, old_irqptr);
  377.    }
  378.  
  379.    old_irqptr = NULL;
  380.  
  381.    /* Mask DSP interrupt */
  382.    tm = inp(0x21);
  383.    outb(0x21,tm | (1 << status.irq));
  384.  
  385. }
  386.  
  387.  
  388. /*
  389.  * MSF - If you are not using MSC 5.1 compat C compiler then following
  390.  *       will need changes. See PORTING document.
  391.  *
  392.  * This gets called anytime there is an interrupt on the SB IRQ.
  393.  * Great effort is made to service DSP interrupts immediately
  394.  * to keep the buffers flowing and pops small.  I wish the card
  395.  * had a bigger internal buffer so we didn't have to worry.
  396.  */ 
  397. void cdecl interrupt far
  398. sb_intr (void)
  399. {
  400.   int unit = 0;
  401.  
  402. /* MSF - probably dont want to call DOS right not */
  403. /*  DPRINTF (("sb_intr(): Got interrupt on unit %d\n", unit)); */
  404.  
  405.   /*
  406.    * If the DSP is doing a transfer, and the interrupt was on the
  407.    * DSP unit (as opposed to, say, the FM unit), then hurry up and
  408.    * call the function to continue the DSP transfer.
  409.    */
  410.   if (dsp.cont_xfer && unit == DSP_UNIT)
  411.     (*dsp.cont_xfer)();
  412.  
  413.   /*
  414.    * If this Unit is expecting an interrupt, then set the semaphore
  415.    * and wake up the sleeper.  Otherwise, we probably weren't expecting
  416.    * this interrupt, so just ignore it.  This also happens when two
  417.    * interrupts are acked in a row, without sleeping in between.
  418.    * Not really a problem, but there should be a clean way to fix it.
  419.    */
  420.   if (status.wake[unit] != NULL)
  421.     {
  422.       *status.wake[unit] = WOKEN_BY_INTERRUPT;
  423.     }
  424.   else
  425.     {
  426. /* MSF - uncomment at own risk, may invoke DOS at a bad time */
  427. /*      DPRINTF (("sb_intr(): An ignored interrupt!\n")); */
  428.     }
  429.      /* reenable interupts via 8259 */
  430.      /* _disable, _enable turn maskable interrupts off/on */
  431.      _disable();
  432.      outb(0x20,0x20);
  433.      _enable();
  434.  
  435.      return;
  436.  
  437. }
  438.  
  439.  
  440.  
  441. /* Following added by MSF to do timing which UNIX takes for granted! */
  442.  
  443. /* the following sets up constants for cpu independent timer routines */
  444. void init_timers(void)
  445. {
  446.    long i, start, end;
  447.  
  448.    /* loop to 500000, which should take around a 1/2 sec or so */
  449.    /* _bios_timeofday returns # of cycles since midnight or something.
  450.     * there are 18.3 cycles/sec                                         */
  451.    _bios_timeofday(_TIME_GETCLOCK, &start);
  452. #pragma loop_opt(off)
  453.    for(i=0; i< 500000; i++);
  454. #pragma loop_opt(on)
  455.    _bios_timeofday(_TIME_GETCLOCK, &end);
  456.  
  457.    time_const = (500000L*183L)/(end-start)/10;
  458.    DPRINTF(("Time_const=%lu\n",time_const));
  459. }
  460.  
  461.  
  462.  
  463. /* MSF - supposed to wait ten microseconds, although I havent timed it
  464.  *       Probably waits longer, important thing is that you cant write
  465.  *       to the DSP without a delay between writes                    */
  466. void tenmicrosec(void)
  467. {
  468.    int i,length;
  469.    length = ((unsigned long)time_const/100000L)+1;
  470. #pragma loop_opt(off)
  471.    for (i=0; i<length; i++);
  472. #pragma loop_opt(on)
  473. }
  474.  
  475. /*
  476.  * Send one byte to the named Sound Blaster register.
  477.  * The SBDK recommends 3.3 microsecs after an address write,
  478.  * and 23 after a data write.  What they don't tell you is that
  479.  * you also can't READ from the ports too soon, or crash! (Same timing?)
  480.  * Anyway, 10 usecs is as close as we can get, so..
  481.  *
  482.  * NOTE:  This function is wicked.  It ties up the entire machine for
  483.  * over forty microseconds.  This is unacceptable, but I'm not sure how
  484.  * to make it better.  Look for a re-write in future versions.
  485.  * Does 30 microsecs merit a full timeout() proceedure?
  486.  */
  487.  void
  488. sb_sendb (unsigned int select_addr, BYTE reg,
  489.       unsigned int data_addr, BYTE value)
  490. {
  491.   outb (select_addr, reg);
  492.   tenmicrosec();
  493.   outb (data_addr, value);
  494.   tenmicrosec();
  495.   tenmicrosec();
  496.   tenmicrosec();
  497. }
  498.  
  499.  
  500.  
  501. /*
  502.  * MSF - I had to really change this.
  503.  *       Instead of calling the sleep() function in UNIX I just
  504.  *       do a loop which is roughly calibrated to the correct time period
  505.  *       If anyone has suggestions on how this can be done better let me
  506.  *       know.
  507.  *
  508.  *       Patience is ignored.
  509.  *
  510.  */
  511.  int
  512. wait_for_intr (int patience)
  513. {
  514.   int sem = 0;
  515.   int result;
  516.   int unit = 0;
  517.   long i, delay;
  518.  
  519.   DPRINTF (("Waiting for interrupt on unit %d.\n", unit));
  520.   status.wake[unit] = &sem;
  521.  
  522.   sem=WOKEN_BY_TIMEOUT;
  523. /* following designed to wait up to time it takes to fill buffer once */
  524.   delay = (DSP_BUF_SIZE*(time_const/dsp.speed));
  525.  
  526. #pragma loop_opt(off)
  527.   for (i=0; i<delay; i++) {
  528.      if (sem==WOKEN_BY_INTERRUPT) break;
  529.     }
  530. #pragma loop_opt(on)
  531.  
  532.   if (sem == WOKEN_BY_TIMEOUT)
  533.     {
  534.       printf ("sb: Interrupt time out.\n");
  535.       dsp.error = EIO;
  536.       result = FAIL;
  537.     }
  538.   else
  539.     {
  540.       DPRINTF (("Got it!\n"));
  541.       result = GOOD;
  542.     }
  543.  
  544.   return (result);
  545. }
  546.  
  547.  
  548. /*
  549.  * DSP functions.
  550.  */
  551. /*
  552.  * Reset the DSP chip, and initialize all DSP variables back
  553.  * to square one.  This can be done at any time to abort
  554.  * a transfer and break out of locked modes. (Like MIDI UART mode!)
  555.  * Note that resetting the DSP puts the speed back to 8196, but
  556.  * it shouldn't matter because we set the speed in dsp_open.
  557.  * Keep this in mind, though, if you use DSP_IOCTL_RESET from
  558.  * inside a program.
  559.  */
  560. int
  561. dsp_reset (void)
  562. {
  563.   int i, s;
  564.  
  565.   DPRINTF (("Resetting DSP.\n"));
  566.   dsp.used[0] = dsp.used[1] = 0; /* This is only for write; see dsp_read() */
  567.   dsp.full[0] = dsp.full[1] = FALSE;
  568.   dsp.hi = dsp.active = 0;
  569.   dsp.first_block = 1;
  570.   dsp.error = ESUCCESS;
  571.   dsp.cont_xfer = NULL;
  572.   status.wake[DSP_UNIT] = NULL;
  573.  
  574.   /*
  575.    * This is how you reset the DSP, according to the SBDK:
  576.    * Send 0x01 to DSP_RESET (0x226) and wait for three microseconds.
  577.    * Then send a 0x00 to the same port.
  578.    * Poll until DSP_RDAVAIL's most significant bit is set, indicating
  579.    * data ready, then read a byte from DSP_RDDATA.  It should be 0xAA.
  580.    * Allow 100 microseconds for the reset.
  581.    */
  582.   tenmicrosec();        /* Lets things settle down. (necessary?) */
  583.   outb (DSP_RESET, 0x01);
  584.   tenmicrosec();
  585.   outb (DSP_RESET, 0x00);
  586.  
  587.   dsp.error = EIO;
  588.   for (i = DSP_LOOP_MAX; i; i--)
  589.     {
  590.       tenmicrosec();
  591.       if ((inp (DSP_RDAVAIL) & DSP_DATA_AVAIL)
  592.       && ((inp (DSP_RDDATA) & 0xFF) == DSP_READY))
  593.     {
  594.       dsp.error = ESUCCESS;
  595.       break;
  596.     }
  597.     }
  598.   if (dsp.error != ESUCCESS)
  599.     return (FAIL);
  600.   else
  601.     return (GOOD);
  602. }
  603.  
  604. /*
  605.  * MSF - following was changed to deal with 64k segments of MSC.
  606.  *       Follows idea of original code, just looks uglier.
  607.  *       I grab 32k and look for 2 10K buffers in that space which
  608.  *       dont cross a 64k boundary.
  609.  *
  610.  * ORIGINAL COMMENTS (msf)
  611.  *
  612.  * This finds page-safe buffers for the DSP DMA to use.  A single DMA
  613.  * transfer can never cross a 64K page boundary, so we have to get
  614.  * aligned buffers for DMA.  The current method is wasteful, but
  615.  * allows any buffer size up to the full 64K (which is nice).  We grab
  616.  * 3 * 64K in the static global memory_chunk, and find the first 64K
  617.  * alignment in it for the first buffer.  The second buffer starts 64K
  618.  * later, at the next alignment.  Yeah, it's gross, but it's flexible.
  619.  * I'm certainly open to ideas!  (Using cool kernel memory alloc is tricky
  620.  * and not real portable.)
  621.  */
  622.  void
  623. dsp_find_buffers (void)
  624. {
  625.   unsigned long startseg, startoff, startaddr, endaddr, break64k;
  626.  
  627.   /* MSF rewrite */
  628.   /* find 64k boundaries */
  629.   startseg = (unsigned long) ((unsigned long)memory_chunk & 0xffff0000) >> 16;
  630.   startoff = (unsigned long) memory_chunk & 0x0000ffff;
  631.  
  632.   startaddr = startseg*16 + startoff;
  633.   endaddr   = startaddr + sizeof(memory_chunk);
  634.   break64k  = (endaddr >> 16)<<16;
  635.  
  636.   /* break64k holds addr where 64k boundary is within array is */
  637.   /* Three cases now
  638.    *  1) Break is outside memory_chunk
  639.    *  2) Break splits memory_chunk into two pieces, each which can be a buffer
  640.    *  3)  "      "         "        "    "    "   , one of which can hold both
  641.   */
  642.   if (break64k < startaddr)
  643.    {
  644.       dsp.buf[0] = memory_chunk;
  645.       dsp.buf[1] = memory_chunk + DSP_BUF_SIZE;
  646.       dsp.phys_buf[0] = startaddr;
  647.       dsp.phys_buf[1] = startaddr+DSP_BUF_SIZE;
  648.    }
  649.   else if ((break64k-startaddr) > DSP_BUF_SIZE)
  650.    {
  651.       /* enough room for first buffer */
  652.       dsp.buf[0] = memory_chunk;
  653.       dsp.phys_buf[0] = startaddr;
  654.  
  655.       /* now see if break allows another immediately after first,
  656.        * or if we need to move it to 64k break */
  657.       if ( (break64k-startaddr-DSP_BUF_SIZE) > DSP_BUF_SIZE)
  658.        {
  659.      dsp.buf[1] = memory_chunk + DSP_BUF_SIZE;
  660.      dsp.phys_buf[1] = startaddr + DSP_BUF_SIZE;
  661.        }
  662.       else
  663.        {
  664.      dsp.buf[1] = memory_chunk + break64k-startaddr;
  665.      dsp.phys_buf[1] = break64k;
  666.        }
  667.     }
  668.    else
  669.     {
  670.       /* not enough room in first chunk, so both must fit in second */
  671.      dsp.buf[0] = memory_chunk + break64k-startaddr;
  672.      dsp.phys_buf[0] = break64k;
  673.      dsp.buf[1] = dsp.buf[0] +  DSP_BUF_SIZE;
  674.      dsp.phys_buf[1] = dsp.phys_buf[0] + DSP_BUF_SIZE;
  675.     }
  676.  
  677.     /* Whew! Hope that covers all cases */
  678. }
  679.  
  680. /*
  681.  * Start a DMA transfer to/from the DSP.
  682.  * This one needs more explaining than I would like to put in comments,
  683.  * so look at the accompanying documentation, which, of course, hasn't
  684.  * been written yet. :-)
  685.  *
  686.  * This function takes one argument, 'dir' which is either PLAY or
  687.  * RECORD, and starts a DMA transfer of as many bytes as are in
  688.  * dsp.buf[dsp.active].  This allows for partial-buffers.
  689.  *
  690.  * Always call this with interrupts masked.
  691.  */
  692.  void
  693. dsp_dma_start (int dir)
  694. {
  695.   unsigned int count = dsp.used[dsp.active] - 1;
  696.  
  697.   /* Prepare the DMAC.  See sb_regs for defs and more info. */
  698.  
  699.  /* MSF - this is real stupid, but MSC optimization makes writes too fast
  700.       with inline code, so calling dummy function outb() slows it
  701.       down enough ! */
  702.   outb (DMA_MASK_REG, DMA_MASK);
  703.   outb (DMA_CLEAR, 0);
  704.   outb (DMA_MODE, (dir == RECORD) ? DMA_MODE_READ : DMA_MODE_WRITE);
  705.   outb (DMA_PAGE, (dsp.phys_buf[dsp.active] & 0xff0000) >> 16); /* Page */
  706.   outb (DMA_ADDRESS, dsp.phys_buf[dsp.active] & 0x00ff); /* LSB of address */
  707.   outb (DMA_ADDRESS, (dsp.phys_buf[dsp.active] & 0xff00) >> 8);
  708.   outb (DMA_COUNT, count & 0x00ff);
  709.   outb (DMA_COUNT, (count & 0xff00) >> 8);
  710.   outb (DMA_MASK_REG, DMA_UNMASK);
  711.  
  712.  DPRINTF(("Sent DMA instructions for length %d\n",count));
  713.  
  714.   /*
  715.    * The DMAC is ready, now send the commands to the DSP.
  716.    * Notice that there are two entirely different operations for
  717.    * Low and High speed DSP.  With HS, You only have to send the
  718.    * byte-count when it changes, and that requires an extra command
  719.    * (Checking if it's a new size is quicker than always sending it.)
  720.    */
  721.   if (dsp.hispeed)
  722.     {
  723.       DPRINTF (("Starting High-Speed DMA of %d bytes to/from buffer %d.\n",
  724.         dsp.used[dsp.active], dsp.active));
  725.  
  726.       if (count != DSP_BUF_SIZE - 1)
  727.     {
  728.       dsp_command (HIGH_SPEED_SIZE);
  729.       dsp_command (count & 0x00ff);
  730.       dsp_command ((count & 0xff00) >> 8);
  731.     }
  732.       dsp_command (dsp.start_command); /* GO! */
  733.     }
  734.   else                /* Low Speed transfer */
  735.     {
  736.       DPRINTF (("Starting Low-Speed DMA xfer of %d bytes to/from buffer %d.\n",
  737.         dsp.used[dsp.active], dsp.active));
  738.       dsp_command (dsp.start_command);
  739.       dsp_command (count & 0x00ff);
  740.       dsp_command ((count & 0xff00) >> 8); /* GO! */
  741.     }
  742.  
  743.   /* This sets up the function to call at the next interrupt: */
  744.   dsp.cont_xfer = (dir == RECORD) ? dsp_next_read : dsp_next_write;
  745. }
  746.  
  747. /*
  748.  * This is basically the interrupt handler for Playback DMA interrupts.
  749.  * Our first priority is to get the other buffer playing, and worry
  750.  * about the rest after.
  751.  */
  752.  void
  753. dsp_next_write (void)
  754. {
  755.  
  756.   inp (DSP_RDAVAIL);            /* ack interrupt */
  757. /*  DPRINTF (("Got interrupt.  DMA done on buffer %d.\n", dsp.active)); */
  758.   dsp.full[dsp.active] = FALSE; /* Just-played buffer is not full */
  759.   dsp.active ^= 1;
  760.   if (dsp.full[dsp.active])
  761.     {
  762. /*      DPRINTF (("Starting next buffer off..\n")); */
  763.       dsp_dma_start (PLAY);
  764.     }
  765.   else
  766.     {
  767. /*      DPRINTF (("Other buffer is not full.  Clearing cont_xfer..\n")); */
  768.       dsp.cont_xfer = NULL;
  769.     }
  770. }
  771.  
  772. /*
  773.  * This is similar to dsp_next_write(), but for Sampling instead of playback.
  774.  */
  775.  void
  776. dsp_next_read (void)
  777. {
  778.  
  779.   inp (DSP_RDAVAIL);            /* ack interrupt */
  780.   /* The active buffer is currently full of samples */
  781.   dsp.full[dsp.active] = TRUE;
  782.   dsp.used[dsp.active] = 0;
  783.  
  784.   /* Flop to the next buffer and fill it up too, unless it's already full */
  785.   dsp.active ^= 1;
  786.   if (dsp.full[dsp.active])
  787.     {
  788. #ifdef ERROR_ON_OVERRUN
  789.       /*
  790.        * An overrun occurs when we fill up two buffers faster than the
  791.        * user is reading them.  Lossage has to occur.  This may or
  792.        * may not be bad.  For recording, it's bad.  For real-time
  793.        * FFTs and such, it's not a real big deal.
  794.        */
  795.       dsp.error = ERANGE;
  796. #endif
  797.       dsp.cont_xfer = NULL;
  798.     }
  799.   else
  800.     dsp_dma_start (RECORD);
  801. }
  802.  
  803. /*
  804.  * This is the main recording function.  Program flow is tricky with
  805.  * all the double-buffering and interrupts, but such are drivers.
  806.  * To summarize, it starts filling the first buffer when the user
  807.  * requests the first read().  (Filling on the open() call would be silly.)
  808.  * When one buffer is done filling, we fill the other one while copying
  809.  * the fresh data to the user.
  810.  * If the user doesn't read fast enough for that DSP speed, we have an
  811.  * overrun.  See above concerning ERROR_ON_OVERRUN.
  812.  */
  813.  int
  814. dsp_read (BYTE far *ptr, int len)
  815. {
  816.   unsigned int bytecount, hunk_size;
  817.  
  818.  
  819.   /* MSF - if speaker on turn it off */
  820.   if (dsp.speaker_on) dsp_set_voice(OFF);
  821.  
  822.   if (dsp.first_block)
  823.     {
  824.       DPRINTF (("Kicking in first_block DSP read..\n"));
  825.       dsp.first_block = FALSE;
  826.       dsp.start_command = dsp.hispeed ? HS_ADC_8 : ADC_8;
  827.       dsp.used[0] = dsp.used[1] = DSP_BUF_SIZE;    /* Start with both empty */
  828.       dsp_dma_start (RECORD);
  829.     }
  830.  
  831.   /* just read in len bytes into buffer pointed too by ptr */
  832.       bytecount = 0;
  833.  
  834.       /* While there is still data to read, and data in this chunk.. */
  835.       while (bytecount < len)
  836.     {
  837.       if (dsp.error != ESUCCESS)
  838.         return (dsp.error);
  839.       
  840.       while (dsp.full[dsp.hi] == FALSE)
  841.         {
  842.           DPRINTF (("Waiting for buffer %d to fill..\n", dsp.hi));
  843.           wait_for_intr (dsp.timeout);
  844.         }
  845.  
  846.       /* Now we give a piece of the buffer to the user */
  847.       hunk_size = min (len - bytecount,
  848.                DSP_BUF_SIZE - dsp.used[dsp.hi]);
  849.  
  850.       DPRINTF (("Copying %d bytes from buffer %d.\n", hunk_size, dsp.hi));
  851.       memmove( ptr, dsp.buf[dsp.hi]+dsp.used[dsp.hi], hunk_size);
  852.       dsp.used[dsp.hi] += hunk_size;
  853.  
  854.       if (dsp.used[dsp.hi] == DSP_BUF_SIZE)
  855.         {
  856.           DPRINTF (("Drained all of buffer %d.\n", dsp.hi));
  857.           dsp.full[dsp.hi] = FALSE;
  858.           dsp.hi ^= 1;
  859.           dsp.used[dsp.hi] = 0;
  860.         }
  861.       bytecount += hunk_size;
  862.     }            /* While there are bytes left in chunk */
  863.   return (dsp.error);
  864. }
  865.  
  866. /* 
  867.  * Main function for DSP sampling.
  868.  * No such thing as an overrun here, but if the user writes too
  869.  * slowly, we have to restart the DSP buffer ping-pong manually.
  870.  * There will then be gaps, of course.
  871.  */
  872.  
  873.  /* rewrite by MSF for MSC */
  874.  int
  875. dsp_write (BYTE far *ptr, int len)
  876. {
  877.   unsigned int bytecount, hunk_size;
  878.  
  879.   /*
  880.    * If this is the first write() operation for this open(),
  881.    * then figure out the DSP command to use.
  882.    * Have to check if it is High Speed, or one of the compressed modes.
  883.    * If this is the first block of a Compressed sound file,
  884.    * then we have to set the "Reference Bit" in the dsp.command for the
  885.    * first block transfer.
  886.    */
  887.  
  888.   /* MSF - if speaker off turn it on */
  889.   if (!dsp.speaker_on) dsp_set_voice(ON);
  890.   if (dsp.first_block)
  891.     {
  892.       dsp.first_block = FALSE;
  893.       if (dsp.hispeed)
  894.     dsp.start_command = HS_DAC_8;
  895.       else
  896.     {
  897.       dsp.start_command = dsp.compression;
  898.       if (dsp.compression == ADPCM_4
  899.           || dsp.compression == ADPCM_2_6
  900.           || dsp.compression == ADPCM_2)
  901.         dsp.start_command |= 1;
  902.     }
  903.     }
  904.  
  905.       bytecount = 0;
  906.  
  907.       /* While there is still data to write, and data in this chunk.. */
  908.       while (bytecount < len)
  909.     {
  910.       if (dsp.error != ESUCCESS) /* Shouldn't happen */
  911.         return (dsp.error);
  912.  
  913.       hunk_size = min (len - bytecount,
  914.                DSP_BUF_SIZE - dsp.used[dsp.hi]);
  915.       DPRINTF (("Adding %d bytes (%d) to buffer %d.\n",
  916.           hunk_size, dsp.used[dsp.hi], dsp.hi));
  917.       memmove(dsp.buf[dsp.hi]+dsp.used[dsp.hi], ptr, hunk_size);
  918.       dsp.used[dsp.hi] += hunk_size;
  919.  
  920.       if (dsp.used[dsp.hi] == DSP_BUF_SIZE)
  921.         {
  922.           dsp.full[dsp.hi] = TRUE;
  923.           DPRINTF (("Just finished filling buffer %d.\n", dsp.hi));
  924.  
  925.           /*
  926.            * This is true when there are no DMA's currently
  927.            * active.  This is either the first block, or the
  928.            * user is slow about writing.  Start the chain reaction.
  929.            */
  930.           if (dsp.cont_xfer == NULL)
  931.         {
  932.           DPRINTF (("Jump-Starting a fresh DMA...\n"));
  933.           dsp.active = dsp.hi;
  934.           dsp_dma_start (PLAY);
  935.           if (!dsp.hispeed)
  936.             dsp.start_command &= ~1; /* Clear reference bit */
  937.           status.wake[DSP_UNIT] = &dsp.semaphore;
  938.         }
  939.           
  940.           /* If the OTHER buffer is playing, wait for it to finish. */
  941.           if (dsp.active == dsp.hi ^ 1)
  942.         {
  943.           DPRINTF (("Waiting for buffer %d to empty.\n", dsp.active));
  944.           wait_for_intr (dsp.timeout);
  945.         }
  946.           dsp.hi ^= 1;    /* Switch to other buffer */
  947.           dsp.used[dsp.hi] = 0; /* Mark it as empty */
  948.           DPRINTF (("Other buffer (%d) is empty, continuing..\n", dsp.hi));
  949.         }            /* if filled hi buffer */
  950.       bytecount += hunk_size;
  951.     }            /* While there are bytes left in chunk */
  952.   return (dsp.error);
  953. }
  954.  
  955. /*
  956.  * MSF - Call this if you want to make sure everything got written out.
  957.  *
  958.  * Play any bytes in the last waiting write() buffer and wait
  959.  * for all buffers to finish transferring.
  960.  * An even number of bytes is forced to keep the stereo channels
  961.  * straight.  I don't think you'll miss one sample.
  962.  */
  963.  int
  964. dsp_flush_dac (void)
  965. {
  966.   
  967.   DPRINTF (("Flushing last buffer(s).\n"));
  968.   if (dsp.used[dsp.hi] != 0)
  969.     {
  970.       DPRINTF (("Playing the last %d bytes.\n", dsp.used[dsp.hi]));
  971.       if (dsp.in_stereo)
  972.     dsp.used[dsp.hi] &= ~1;    /* Have to have even number of bytes. */
  973.       dsp.full[dsp.hi] = TRUE; 
  974.       if (dsp.cont_xfer == NULL)
  975.     {
  976.       dsp.active = dsp.hi;
  977.       dsp_dma_start (PLAY);
  978.     }
  979.     }
  980.  
  981.   /* Now wait for any transfers to finish up. */
  982.   while (dsp.cont_xfer)
  983.     {
  984.       DPRINTF (("Waiting for last DMA(s) to finish.\n"));
  985.       wait_for_intr (dsp.timeout);
  986.     }
  987.   return (ESUCCESS);
  988. }
  989.  
  990.  
  991.  int
  992. dsp_open (void)
  993. {
  994. #ifdef FULL_DEBUG
  995.   int i;
  996. #endif
  997.  
  998.   status.dsp_in_use = TRUE;
  999.   dsp_reset ();            /* Resets card and inits variables */
  1000.   dsp_set_speed (&dsp.speed);    /* Set SB back to the current speed. */
  1001.   dsp_set_voice(SPEAKER_ON);    /* MSF - turn on speaker by default */
  1002.  
  1003.   /*
  1004.    * In case we do any High-Speed transfers, this sets the transfer
  1005.    * size.  We only need to set it when it changes.  See dsp_dma_start()
  1006.    */
  1007.   dsp_command (HIGH_SPEED_SIZE);
  1008.   dsp_command ((DSP_BUF_SIZE - 1) & 0x00ff);
  1009.   dsp_command (((DSP_BUF_SIZE - 1) & 0xff00) >> 8);
  1010.  
  1011. #ifdef FULL_DEBUG
  1012.   /* Stuff buffers with loud garbage so we can hear/see leaks. */
  1013.   for (i = 0; i < DSP_BUF_SIZE; i++)
  1014.     dsp.buf[0][i] = dsp.buf[1][i] = i & 0xff;
  1015. #endif
  1016.   return (ESUCCESS);
  1017. }
  1018.  
  1019.  
  1020. /* MSF - I dont think this is really needed. Just left it in just in case */
  1021.  int
  1022. dsp_close (int flags)
  1023. {
  1024.   if (status.dsp_in_use)
  1025.     {
  1026.       /* Wait for any last write buffers to empty  */
  1027.       dsp_flush_dac ();
  1028.       dsp_reset ();
  1029.       status.dsp_in_use = FALSE;
  1030.       return (ESUCCESS);
  1031.     }
  1032.   else
  1033.     return (ESRCH);        /* Does this ever happen? */
  1034. }
  1035.  
  1036.  
  1037. /*
  1038.  * Set the playback/recording speed of the DSP.
  1039.  * This takes a pointer to an integer between DSP_MIN_SPEED
  1040.  * and DSP_MAX_SPEED and changes that value to the actual speed
  1041.  * you got. (Since the speed is so darn granular.)
  1042.  * This also sets the dsp.hispeed flag appropriately.
  1043.  * Note that Hi-Speed and compression are mutually exclusive!
  1044.  * I also don't check all the different range limits that
  1045.  * compression imposes.  Supposedly, the DSP can't play compressed
  1046.  * data as fast, but that's your problem.  It will just run slower.
  1047.  * Hmmm.. that could cause interrupt timeouts, I suppose.
  1048.  */
  1049.  /* Changed by MSF to use unsigned int, still pass -1 (65535) to query speed
  1050.  */
  1051. unsigned int dsp_set_speed (unsigned int *speed) {
  1052.    BYTE time_constant;
  1053.  
  1054.  if (*speed == -1)
  1055.     {
  1056.       *speed = dsp.speed;
  1057.       return (ESUCCESS);
  1058.     }
  1059.   
  1060.   if (*speed < DSP_MIN_SPEED || *speed > DSP_MAX_SPEED)
  1061.     {
  1062.       DPRINTF (("Attempt to set invalid speed (%ud)\n", *speed));
  1063.       return (EINVAL);
  1064.     }
  1065.  
  1066.   if (*speed > MAX_LOW_SPEED)
  1067.     {
  1068.       if (dsp.compression != PCM_8)
  1069.     return (EINVAL);
  1070.       DPRINTF (("Using HiSpeed mode.\n"));
  1071.       time_constant = (BYTE) ((65536L - (256000000L / (long)*speed)) >> 8);
  1072.       dsp.speed = (256000000L / (65536L - ((long)time_constant << 8)));
  1073.       dsp.hispeed = TRUE;
  1074.     }
  1075.   else
  1076.     {
  1077.       DPRINTF (("Using LowSpeed mode.\n"));
  1078.       time_constant = (BYTE) (256 - (1000000 / *speed));
  1079.       dsp.speed = 1000000 / (256 - time_constant);
  1080.       dsp.hispeed = FALSE;
  1081.     }
  1082.  
  1083.   /* Here is where we actually set the card's speed */
  1084.   if (dsp_command (SET_TIME_CONSTANT) == FAIL
  1085.       || dsp_command (time_constant) == FAIL)
  1086.     return (EIO);
  1087.   /*
  1088.    * Replace speed with the speed we actually got.
  1089.    * Set the DSP timeout to be twice as long as a full
  1090.    * buffer should take.
  1091.    */
  1092.   *speed = dsp.speed;
  1093.   dsp.timeout = DSP_BUF_SIZE * HZ * 2 / dsp.speed;
  1094.   DPRINTF (("Speed set to %d.\n", dsp.speed));
  1095.   return (ESUCCESS);
  1096. }
  1097.  
  1098.  
  1099. /*
  1100.  * Turn the DSP output speaker on and off.
  1101.  * Argument of zero turns it off, on otherwise
  1102.  */
  1103.  int
  1104. dsp_set_voice (int on)
  1105. {
  1106.   if (dsp_command (on ? SPEAKER_ON : SPEAKER_OFF) == GOOD)
  1107.    {
  1108.     dsp.speaker_on = on ? TRUE : FALSE;
  1109.     return (ESUCCESS);
  1110.    }
  1111.   else
  1112.     return (EIO);
  1113. }
  1114.  
  1115. /*
  1116.  * Set the DAC hardware decompression mode.
  1117.  * No compression allowed for Hi-Speed mode, of course.
  1118.  */
  1119.  int
  1120. dsp_set_compression (int mode)
  1121. {
  1122.   switch (mode)
  1123.     {
  1124.     case ADPCM_4:
  1125.     case ADPCM_2_6:
  1126.     case ADPCM_2:
  1127.       if (dsp.hispeed)
  1128.     return (EINVAL);      /* Fall through.. */
  1129.     case PCM_8:
  1130.       dsp.compression = mode;
  1131.       return (ESUCCESS);
  1132.       
  1133.     default:
  1134.       return (EINVAL);
  1135.     }
  1136. }
  1137.  
  1138. /*
  1139.  * Send a command byte to the DSP port.
  1140.  * First poll the DSP_STATUS port until the BUSY bit clears,
  1141.  * then send the byte to the DSP_COMMAND port.
  1142.  */
  1143.  int
  1144. dsp_command (BYTE val)
  1145. {
  1146.   int i;
  1147.  
  1148. #ifdef FULL_DEBUG
  1149.   printf ("Sending DSP command 0x%X\n", val);
  1150. #endif
  1151.   for (i = DSP_LOOP_MAX; i; i--)
  1152.     {
  1153.       if ((inp (DSP_STATUS) & DSP_BUSY) == 0)
  1154.     {
  1155.       outb(DSP_COMMAND, val);
  1156.       return (GOOD);
  1157.     }
  1158.       tenmicrosec ();
  1159.     }
  1160.   printf ("sb: dsp_command (%2X) failed!\n", val);
  1161.   return (FAIL);
  1162. }
  1163.  
  1164. /*
  1165.  * This turns stereo playback/recording on and off.
  1166.  * For playback, it seems to only be a bit in the mixer.
  1167.  * I don't know the secret to stereo sampling, so this may
  1168.  * need reworking.  If YOU know how to sample in stereo, send Email!
  1169.  * Maybe this should be a Mixer parameter, but I really don't think so.
  1170.  * It's a DSP Thing, isn't it?  Hmm..
  1171.  */
  1172.  int
  1173. dsp_set_stereo (FLAG select)
  1174. {
  1175.   dsp.in_stereo = !!select;
  1176.   /* Have to preserve DNFI bit from OUT_FILTER */
  1177.   mixer_send (CHANNELS, ((mixer_read_reg (OUT_FILTER) & ~STEREO_DAC)
  1178.              | (dsp.in_stereo ? STEREO_DAC : MONO_DAC)));
  1179.   return (ESUCCESS);
  1180. }
  1181.  
  1182.  
  1183. /*
  1184.  * Sets mixer volume levels.
  1185.  * All levels except mic are 0 to 15, mic is 7.  See sbinfo.doc
  1186.  * for details on granularity and such.
  1187.  * Basically, the mixer forces the lowest bit high, effectively
  1188.  * reducing the possible settings by one half.  Yes, that's right,
  1189.  * volume levels have 8 settings, and microphone has four.  Sucks.
  1190.  */
  1191.  int
  1192. mixer_set_levels (struct sb_mixer_levels *l)
  1193. {
  1194.   if (l->master.l & ~0xF || l->master.r & ~0xF
  1195.       || l->line.l & ~0xF || l->line.r & ~0xF
  1196.       || l->voc.l & ~0xF || l->voc.r & ~0xF
  1197.       || l->fm.l & ~0xF || l->fm.r & ~0xF
  1198.       || l->cd & ~0xF
  1199.       || l->mic & ~0x7)
  1200.     return (EINVAL);
  1201.  
  1202.   mixer_send (VOL_MASTER, (l->master.l << 4) | l->master.r);
  1203.   mixer_send (VOL_LINE, (l->line.l << 4) | l->line.r);
  1204.   mixer_send (VOL_VOC, (l->voc.l << 4) | l->voc.r);
  1205.   mixer_send (VOL_FM, (l->fm.l << 4) | l->fm.r);
  1206.   mixer_send (VOL_CD, l->cd);
  1207.   mixer_send (VOL_MIC, l->mic);
  1208.   return (ESUCCESS);
  1209. }
  1210.  
  1211. /*
  1212.  * This sets aspects of the Mixer that are not volume levels.
  1213.  * (Recording source, filter level, I/O filtering, and stereo.)
  1214.  */
  1215.  int
  1216. mixer_set_params (struct sb_mixer_params *p)
  1217. {
  1218.   if (p->record_source != SRC_MIC
  1219.       && p->record_source != SRC_CD
  1220.       && p->record_source != SRC_LINE)
  1221.     return (EINVAL);
  1222.  
  1223.   /*
  1224.    * I'm not sure if this is The Right Thing.  Should stereo
  1225.    * be entirely under control of DSP?  I like being able to toggle
  1226.    * it while a sound is playing, so I do this... because I can.
  1227.    */
  1228.   dsp.in_stereo = !!p->dsp_stereo;
  1229.  
  1230.   mixer_send (RECORD_SRC, (p->record_source
  1231.                | (p->hifreq_filter ? FREQ_HI : FREQ_LOW)
  1232.                | (p->filter_input ? FILT_ON : FILT_OFF)));
  1233.  
  1234.   mixer_send (OUT_FILTER, ((dsp.in_stereo ? STEREO_DAC : MONO_DAC)
  1235.                | (p->filter_output ? FILT_ON : FILT_OFF)));
  1236.   return (ESUCCESS);
  1237. }
  1238.  
  1239. /*
  1240.  * Read the current mixer level settings into the user's struct.
  1241.  */
  1242.  int
  1243. mixer_get_levels (struct sb_mixer_levels *l)
  1244. {
  1245.   BYTE val;
  1246.  
  1247.   val = mixer_read_reg (VOL_MASTER); /* Master */
  1248.   l->master.l = B4(val >> 4);
  1249.   l->master.r = B4(val);
  1250.  
  1251.   val = mixer_read_reg (VOL_LINE); /* FM */
  1252.   l->line.l = B4(val >> 4);
  1253.   l->line.r = B4(val);
  1254.   
  1255.   val = mixer_read_reg (VOL_VOC); /* DAC */
  1256.   l->voc.l = B4(val >> 4);
  1257.   l->voc.r = B4(val);
  1258.  
  1259.   val = mixer_read_reg (VOL_FM); /* FM */
  1260.   l->fm.l = B4(val >> 4);
  1261.   l->fm.r = B4(val);
  1262.   
  1263.   val = mixer_read_reg (VOL_CD); /* CD */
  1264.   l->cd = B4(val);
  1265.  
  1266.   val = mixer_read_reg (VOL_MIC); /* Microphone */
  1267.   l->mic = B3(val);
  1268.  
  1269.   return (ESUCCESS);
  1270. }
  1271.  
  1272. /*
  1273.  * Read the current mixer parameters into the user's struct.
  1274.  */
  1275.  int
  1276. mixer_get_params (struct sb_mixer_params *params)
  1277. {
  1278.   BYTE val;
  1279.  
  1280.   val = mixer_read_reg (RECORD_SRC);
  1281.   params->record_source = val & 0x07;
  1282.   params->hifreq_filter = !!(val & FREQ_HI);
  1283.   params->filter_input = (val & FILT_OFF) ? OFF : ON;
  1284.   params->filter_output = (mixer_read_reg (OUT_FILTER) & FILT_OFF) ? OFF : ON;
  1285.   params->dsp_stereo = dsp.in_stereo;
  1286.   return (ESUCCESS);
  1287. }
  1288.  
  1289. /*
  1290.  * This is supposed to reset the mixer.
  1291.  * Technically, a reset is performed by sending a byte to the MIXER_RESET
  1292.  * register, but I don't like the default power-up settings, so I use
  1293.  * these.  Adjust to taste, and you have your own personalized mixer_reset
  1294.  * ioctl.
  1295.  */
  1296.  int
  1297. mixer_reset (void)
  1298. {
  1299.   struct sb_mixer_levels l;
  1300.   struct sb_mixer_params p;
  1301.  
  1302.   p.filter_input  = OFF;
  1303.   p.filter_output = OFF;
  1304.   p.hifreq_filter = TRUE;
  1305.   p.record_source = SRC_LINE;
  1306.  
  1307.   l.cd = 1;
  1308.   l.mic = 1;
  1309.   l.master.l = l.master.r = 11;
  1310.   l.line.l = l.line.r = 15;
  1311.   l.fm.l = l.fm.r = 15;
  1312.   l.voc.l = l.voc.r = 15;
  1313.  
  1314.   if (mixer_set_levels (&l) == ESUCCESS
  1315.       && mixer_set_params (&p) == ESUCCESS)
  1316.     return (ESUCCESS);
  1317.   else
  1318.     return (EIO);
  1319. }
  1320.  
  1321. /*
  1322.  * Send a byte 'val' to the Mixer register 'reg'.
  1323.  */
  1324.  void
  1325. mixer_send (BYTE reg, BYTE val)
  1326. {
  1327. #if FULL_DEBUG
  1328.   printf ("%02x: %02x\n", reg, val);
  1329. #endif
  1330.   sb_sendb (MIXER_ADDR, reg, MIXER_DATA, val);
  1331. }
  1332.  
  1333. /*
  1334.  * Returns the contents of the mixer register 'reg'.
  1335.  */
  1336.  BYTE
  1337. mixer_read_reg (BYTE reg)
  1338. {
  1339.   outb (MIXER_ADDR, reg);
  1340.   tenmicrosec();        /* To make sure nobody reads too soon */
  1341.   return (inp (MIXER_DATA));
  1342. }
  1343.  
  1344.  
  1345.  
  1346. /* MSF - added because I was sending stuff to the DMA registers too
  1347.  *       fast when MSC put in inline out dx,ax commands. This subroutine
  1348.  *       slows things down, maybe too much. Suggestions welcome. */
  1349. void outb(int x, int y)
  1350. {
  1351. outp(x,y);
  1352. }
  1353.