wavfile.c 37.5 KB
Newer Older
1
/*
2
 * Copyright 2002 Michael Günnewig
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17 18
 */

19
#define COBJMACROS
20
#include <assert.h>
21
#include <stdarg.h>
22

23
#include "windef.h"
24
#include "winbase.h"
25
#include "wingdi.h"
26 27 28 29 30
#include "winuser.h"
#include "winnls.h"
#include "winerror.h"
#include "mmsystem.h"
#include "vfw.h"
31
#include "msacm.h"
32 33 34 35

#include "avifile_private.h"
#include "extrachunk.h"

36
#include "wine/unicode.h"
37 38 39 40 41 42 43 44 45 46 47 48 49
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(avifile);

/***********************************************************************/

#define formtypeWAVE    mmioFOURCC('W','A','V','E')
#define ckidWAVEFORMAT  mmioFOURCC('f','m','t',' ')
#define ckidWAVEFACT    mmioFOURCC('f','a','c','t')
#define ckidWAVEDATA    mmioFOURCC('d','a','t','a')

/***********************************************************************/

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#define ENDIAN_SWAPWORD(x)  ((((x) >> 8) & 0xFF) | (((x) & 0xFF) << 8))
#define ENDIAN_SWAPDWORD(x) (ENDIAN_SWAPWORD((x >> 16) & 0xFFFF) | \
                             ENDIAN_SWAPWORD(x & 0xFFFF) << 16)

#ifdef WORDS_BIGENDIAN
#define BE2H_WORD(x)  (x)
#define BE2H_DWORD(x) (x)
#define LE2H_WORD(x)  ENDIAN_SWAPWORD(x)
#define LE2H_DWORD(x) ENDIAN_SWAPDWORD(x)
#else
#define BE2H_WORD(x)  ENDIAN_SWAPWORD(x)
#define BE2H_DWORD(x) ENDIAN_SWAPDWORD(x)
#define LE2H_WORD(x)  (x)
#define LE2H_DWORD(x) (x)
#endif

typedef struct {
  FOURCC  fccType;
  DWORD   offset;
  DWORD   size;
  INT     encoding;
  DWORD   sampleRate;
  DWORD   channels;
} SUNAUDIOHEADER;

#define AU_ENCODING_ULAW_8                 1
#define AU_ENCODING_PCM_8                  2
#define AU_ENCODING_PCM_16                 3
#define AU_ENCODING_PCM_24                 4
#define AU_ENCODING_PCM_32                 5
#define AU_ENCODING_FLOAT                  6
#define AU_ENCODING_DOUBLE                 7
#define AU_ENCODING_ADPCM_G721_32         23
#define AU_ENCODING_ADPCM_G722            24
#define AU_ENCODING_ADPCM_G723_24         25
#define AU_ENCODING_ADPCM_G723_5          26
#define AU_ENCODING_ALAW_8                27

/***********************************************************************/

90 91
typedef struct _IAVIFileImpl {
  IUnknown          IUnknown_inner;
92
  IAVIFile          IAVIFile_iface;
93
  IPersistFile      IPersistFile_iface;
94
  IAVIStream        IAVIStream_iface;
95 96
  IUnknown          *outer_unk;
  LONG              ref;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  /* IAVIFile, IAVIStream stuff... */
  AVIFILEINFOW      fInfo;
  AVISTREAMINFOW    sInfo;

  LPWAVEFORMATEX    lpFormat;
  LONG              cbFormat;

  MMCKINFO          ckData;

  EXTRACHUNKS       extra;

  /* IPersistFile stuff ... */
  HMMIO             hmmio;
  LPWSTR            szFileName;
  UINT              uMode;
  BOOL              fDirty;
113
} IAVIFileImpl;
114 115 116 117 118

/***********************************************************************/

static HRESULT AVIFILE_LoadFile(IAVIFileImpl *This);
static HRESULT AVIFILE_LoadSunFile(IAVIFileImpl *This);
119
static HRESULT AVIFILE_SaveFile(const IAVIFileImpl *This);
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
static inline IAVIFileImpl *impl_from_IUnknown(IUnknown *iface)
{
    return CONTAINING_RECORD(iface, IAVIFileImpl, IUnknown_inner);
}

static HRESULT WINAPI IUnknown_fnQueryInterface(IUnknown *iface, REFIID riid, void **ret_iface)
{
    IAVIFileImpl *This = impl_from_IUnknown(iface);

    TRACE("(%p,%s,%p)\n", This, debugstr_guid(riid), ret_iface);

    if (IsEqualGUID(&IID_IUnknown, riid))
        *ret_iface = &This->IUnknown_inner;
    else if (IsEqualGUID(&IID_IAVIFile, riid))
        *ret_iface = &This->IAVIFile_iface;
    else if (IsEqualGUID(&IID_IAVIStream, riid))
137
        *ret_iface = &This->IAVIStream_iface;
138
    else if (IsEqualGUID(&IID_IPersistFile, riid))
139
        *ret_iface = &This->IPersistFile_iface;
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    else {
        WARN("(%p)->(%s %p)\n", This, debugstr_guid(riid), ret_iface);
        *ret_iface = NULL;
        return E_NOINTERFACE;
    }

    /* Violation of the COM aggregation ref counting rule */
    IUnknown_AddRef(&This->IUnknown_inner);
    return S_OK;
}

static ULONG WINAPI IUnknown_fnAddRef(IUnknown *iface)
{
    IAVIFileImpl *This = impl_from_IUnknown(iface);
    ULONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    return ref;
}

static ULONG WINAPI IUnknown_fnRelease(IUnknown *iface)
{
    IAVIFileImpl *This = impl_from_IUnknown(iface);
    ULONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    if (!ref) {
        /* need to write headers to file */
        if (This->fDirty)
            AVIFILE_SaveFile(This);

        HeapFree(GetProcessHeap(), 0, This->lpFormat);
        This->lpFormat = NULL;
        This->cbFormat = 0;
        HeapFree(GetProcessHeap(), 0, This->extra.lp);
        This->extra.lp = NULL;
        This->extra.cb = 0;
        HeapFree(GetProcessHeap(), 0, This->szFileName);
        This->szFileName = NULL;
        if (This->hmmio) {
            mmioClose(This->hmmio, 0);
            This->hmmio = NULL;
        }
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

static const IUnknownVtbl unk_vtbl =
{
    IUnknown_fnQueryInterface,
    IUnknown_fnAddRef,
    IUnknown_fnRelease
};

198 199 200 201 202
static inline IAVIFileImpl *impl_from_IAVIFile(IAVIFile *iface)
{
    return CONTAINING_RECORD(iface, IAVIFileImpl, IAVIFile_iface);
}

203
static HRESULT WINAPI IAVIFile_fnQueryInterface(IAVIFile *iface, REFIID riid, void **ret_iface)
204
{
205
    IAVIFileImpl *This = impl_from_IAVIFile(iface);
206

207
    return IUnknown_QueryInterface(This->outer_unk, riid, ret_iface);
208 209 210 211
}

static ULONG WINAPI IAVIFile_fnAddRef(IAVIFile *iface)
{
212
    IAVIFileImpl *This = impl_from_IAVIFile(iface);
213

214
    return IUnknown_AddRef(This->outer_unk);
215 216 217 218
}

static ULONG WINAPI IAVIFile_fnRelease(IAVIFile *iface)
{
219
    IAVIFileImpl *This = impl_from_IAVIFile(iface);
220

221
    return IUnknown_Release(This->outer_unk);
222 223
}

224
static HRESULT WINAPI IAVIFile_fnInfo(IAVIFile *iface, AVIFILEINFOW *afi, LONG size)
225
{
226
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
227

228
  TRACE("(%p,%p,%d)\n",iface,afi,size);
229 230 231 232 233 234 235 236 237 238

  if (afi == NULL)
    return AVIERR_BADPARAM;
  if (size < 0)
    return AVIERR_BADSIZE;

  /* update file info */
  This->fInfo.dwFlags = 0;
  This->fInfo.dwCaps  = AVIFILECAPS_CANREAD|AVIFILECAPS_CANWRITE;
  if (This->lpFormat != NULL) {
239 240
    assert(This->sInfo.dwScale != 0);

241 242 243 244 245
    This->fInfo.dwStreams             = 1;
    This->fInfo.dwScale               = This->sInfo.dwScale;
    This->fInfo.dwRate                = This->sInfo.dwRate;
    This->fInfo.dwLength              = This->sInfo.dwLength;
    This->fInfo.dwSuggestedBufferSize = This->ckData.cksize;
246 247
    This->fInfo.dwMaxBytesPerSec =
      MulDiv(This->sInfo.dwSampleSize,This->sInfo.dwRate,This->sInfo.dwScale);
248 249
  }

250
  memcpy(afi, &This->fInfo, min((DWORD)size, sizeof(This->fInfo)));
251

252
  if ((DWORD)size < sizeof(This->fInfo))
253 254 255 256
    return AVIERR_BUFFERTOOSMALL;
  return AVIERR_OK;
}

257 258
static HRESULT WINAPI IAVIFile_fnGetStream(IAVIFile *iface, IAVIStream **avis, DWORD fccType,
        LONG lParam)
259
{
260
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
261

262
  TRACE("(%p,%p,0x%08X,%d)\n", iface, avis, fccType, lParam);
263 264 265 266 267 268 269 270 271 272 273 274 275

  /* check parameter */
  if (avis == NULL)
    return AVIERR_BADPARAM;

  *avis = NULL;

  /* Does our stream exists? */
  if (lParam != 0 || This->fInfo.dwStreams == 0)
    return AVIERR_NODATA;
  if (fccType != 0 && fccType != streamtypeAUDIO)
    return AVIERR_NODATA;

276
  *avis = &This->IAVIStream_iface;
277
  IAVIStream_AddRef(*avis);
278 279 280 281

  return AVIERR_OK;
}

282 283
static HRESULT WINAPI IAVIFile_fnCreateStream(IAVIFile *iface, IAVIStream **avis,
        AVISTREAMINFOW *asi)
284
{
285
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

  TRACE("(%p,%p,%p)\n", iface, avis, asi);

  /* check parameters */
  if (avis == NULL || asi == NULL)
    return AVIERR_BADPARAM;

  *avis = NULL;

  /* We only support one audio stream */
  if (This->fInfo.dwStreams != 0 || This->lpFormat != NULL)
    return AVIERR_UNSUPPORTED;
  if (asi->fccType != streamtypeAUDIO)
    return AVIERR_UNSUPPORTED;

  /* Does the user have write permission? */
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

  This->cbFormat = 0;
  This->lpFormat = NULL;

  memcpy(&This->sInfo, asi, sizeof(This->sInfo));

  /* make sure streaminfo if okay for us */
  This->sInfo.fccHandler          = 0;
  This->sInfo.dwFlags             = 0;
  This->sInfo.dwCaps              = AVIFILECAPS_CANREAD|AVIFILECAPS_CANWRITE;
  This->sInfo.dwStart             = 0;
  This->sInfo.dwInitialFrames     = 0;
  This->sInfo.dwFormatChangeCount = 0;
  memset(&This->sInfo.rcFrame, 0, sizeof(This->sInfo.rcFrame));

  This->fInfo.dwStreams = 1;
  This->fInfo.dwScale   = This->sInfo.dwScale;
  This->fInfo.dwRate    = This->sInfo.dwRate;
  This->fInfo.dwLength  = This->sInfo.dwLength;

  This->ckData.dwDataOffset = 0;
  This->ckData.cksize       = 0;

327
  *avis = &This->IAVIStream_iface;
328
  IAVIStream_AddRef(*avis);
329 330 331 332

  return AVIERR_OK;
}

333
static HRESULT WINAPI IAVIFile_fnWriteData(IAVIFile *iface, DWORD ckid, void *lpData, LONG size)
334
{
335
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
336

337
  TRACE("(%p,0x%08X,%p,%d)\n", iface, ckid, lpData, size);
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

  /* check parameters */
  if (lpData == NULL)
    return AVIERR_BADPARAM;
  if (size < 0)
    return AVIERR_BADSIZE;

  /* Do we have write permission? */
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

  This->fDirty = TRUE;

  return WriteExtraChunk(&This->extra, ckid, lpData, size);
}

354
static HRESULT WINAPI IAVIFile_fnReadData(IAVIFile *iface, DWORD ckid, void *lpData, LONG *size)
355
{
356
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
357

358
  TRACE("(%p,0x%08X,%p,%p)\n", iface, ckid, lpData, size);
359 360 361 362 363 364 365 366 367 368 369 370 371 372

  return ReadExtraChunk(&This->extra, ckid, lpData, size);
}

static HRESULT WINAPI IAVIFile_fnEndRecord(IAVIFile *iface)
{
  TRACE("(%p)\n",iface);

  /* This is only needed for interleaved files.
   * We have only one stream, which can't be interleaved.
   */
  return AVIERR_OK;
}

373
static HRESULT WINAPI IAVIFile_fnDeleteStream(IAVIFile *iface, DWORD fccType, LONG lParam)
374
{
375
  IAVIFileImpl *This = impl_from_IAVIFile(iface);
376

377
  TRACE("(%p,0x%08X,%d)\n", iface, fccType, lParam);
378 379 380 381 382

  /* check parameter */
  if (lParam < 0)
    return AVIERR_BADPARAM;

383
  /* Do we have our audio stream? */
384 385 386 387 388 389 390 391
  if (lParam != 0 || This->fInfo.dwStreams == 0 ||
      (fccType != 0 && fccType != streamtypeAUDIO))
    return AVIERR_NODATA;

  /* Have user write permissions? */
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

392
  HeapFree(GetProcessHeap(), 0, This->lpFormat);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  This->lpFormat = NULL;
  This->cbFormat = 0;

  /* update infos */
  This->ckData.dwDataOffset = 0;
  This->ckData.cksize       = 0;

  This->sInfo.dwScale   = 0;
  This->sInfo.dwRate    = 0;
  This->sInfo.dwLength  = 0;
  This->sInfo.dwSuggestedBufferSize = 0;

  This->fInfo.dwStreams = 0;
  This->fInfo.dwEditCount++;

  This->fDirty = TRUE;

  return AVIERR_OK;
}

413 414 415 416 417 418 419 420 421 422 423 424 425
static const struct IAVIFileVtbl iwavft = {
    IAVIFile_fnQueryInterface,
    IAVIFile_fnAddRef,
    IAVIFile_fnRelease,
    IAVIFile_fnInfo,
    IAVIFile_fnGetStream,
    IAVIFile_fnCreateStream,
    IAVIFile_fnWriteData,
    IAVIFile_fnReadData,
    IAVIFile_fnEndRecord,
    IAVIFile_fnDeleteStream
};

426 427
/***********************************************************************/

428
static inline IAVIFileImpl *impl_from_IPersistFile(IPersistFile *iface)
429
{
430 431
    return CONTAINING_RECORD(iface, IAVIFileImpl, IPersistFile_iface);
}
432

433 434 435 436
static HRESULT WINAPI IPersistFile_fnQueryInterface(IPersistFile *iface, REFIID riid,
        void **ret_iface)
{
    IAVIFileImpl *This = impl_from_IPersistFile(iface);
437

438
    return IUnknown_QueryInterface(This->outer_unk, riid, ret_iface);
439 440 441 442
}

static ULONG   WINAPI IPersistFile_fnAddRef(IPersistFile *iface)
{
443
    IAVIFileImpl *This = impl_from_IPersistFile(iface);
444

445
    return IUnknown_AddRef(This->outer_unk);
446 447 448 449
}

static ULONG   WINAPI IPersistFile_fnRelease(IPersistFile *iface)
{
450
    IAVIFileImpl *This = impl_from_IPersistFile(iface);
451

452
    return IUnknown_Release(This->outer_unk);
453 454 455 456 457 458 459 460 461 462
}

static HRESULT WINAPI IPersistFile_fnGetClassID(IPersistFile *iface,
						LPCLSID pClassID)
{
  TRACE("(%p,%p)\n", iface, pClassID);

  if (pClassID == NULL)
    return AVIERR_BADPARAM;

463
  *pClassID = CLSID_WAVFile;
464 465 466 467 468 469

  return AVIERR_OK;
}

static HRESULT WINAPI IPersistFile_fnIsDirty(IPersistFile *iface)
{
470
    IAVIFileImpl *This = impl_from_IPersistFile(iface);
471

472
    TRACE("(%p)\n", iface);
473

474
    return (This->fDirty ? S_OK : S_FALSE);
475 476
}

477
static HRESULT WINAPI IPersistFile_fnLoad(IPersistFile *iface, LPCOLESTR pszFileName, DWORD dwMode)
478
{
479
  IAVIFileImpl *This = impl_from_IPersistFile(iface);
480 481 482
  WCHAR wszStreamFmt[50];
  INT   len;

483
  TRACE("(%p,%s,0x%08X)\n", iface, debugstr_w(pszFileName), dwMode);
484 485 486 487 488

  /* check parameter */
  if (pszFileName == NULL)
    return AVIERR_BADPARAM;

489
  if (This->hmmio != NULL)
490 491
    return AVIERR_ERROR; /* No reuse of this object for another file! */

Austin English's avatar
Austin English committed
492
  /* remember mode and name */
493 494 495
  This->uMode = dwMode;

  len = lstrlenW(pszFileName) + 1;
496
  This->szFileName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
497 498 499 500 501 502
  if (This->szFileName == NULL)
    return AVIERR_MEMORY;
  lstrcpyW(This->szFileName, pszFileName);

  /* try to open the file */
  This->hmmio = mmioOpenW(This->szFileName, NULL, MMIO_ALLOCBUF | dwMode);
503 504
  if (This->hmmio == NULL) {
    /* mmioOpenW not in native DLLs of Win9x -- try mmioOpenA */
505 506 507
    LPSTR szFileName;
    len = WideCharToMultiByte(CP_ACP, 0, This->szFileName, -1,
                              NULL, 0, NULL, NULL);
508
    szFileName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR));
509 510 511 512 513 514 515
    if (szFileName == NULL)
      return AVIERR_MEMORY;

    WideCharToMultiByte(CP_ACP, 0, This->szFileName, -1, szFileName,
			len, NULL, NULL);

    This->hmmio = mmioOpenA(szFileName, NULL, MMIO_ALLOCBUF | dwMode);
516
    HeapFree(GetProcessHeap(), 0, szFileName);
517 518 519
    if (This->hmmio == NULL)
      return AVIERR_FILEOPEN;
  }
520 521 522 523 524

  memset(& This->fInfo, 0, sizeof(This->fInfo));
  memset(& This->sInfo, 0, sizeof(This->sInfo));

  LoadStringW(AVIFILE_hModule, IDS_WAVEFILETYPE, This->fInfo.szFileType,
525
	      sizeof(This->fInfo.szFileType)/sizeof(This->fInfo.szFileType[0]));
526
  if (LoadStringW(AVIFILE_hModule, IDS_WAVESTREAMFORMAT,
527
		  wszStreamFmt, sizeof(wszStreamFmt)/sizeof(wszStreamFmt[0])) > 0) {
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    wsprintfW(This->sInfo.szName, wszStreamFmt,
	      AVIFILE_BasenameW(This->szFileName));
  }

  /* should we create a new file? */
  if (dwMode & OF_CREATE) {
    /* nothing more to do */
    return AVIERR_OK;
  } else
    return AVIFILE_LoadFile(This);
}

static HRESULT WINAPI IPersistFile_fnSave(IPersistFile *iface,
					  LPCOLESTR pszFileName,BOOL fRemember)
{
  TRACE("(%p,%s,%d)\n", iface, debugstr_w(pszFileName), fRemember);

  /* We write directly to disk, so nothing to do. */

  return AVIERR_OK;
}

static HRESULT WINAPI IPersistFile_fnSaveCompleted(IPersistFile *iface,
						   LPCOLESTR pszFileName)
{
  TRACE("(%p,%s)\n", iface, debugstr_w(pszFileName));

  /* We write directly to disk, so nothing to do. */

  return AVIERR_OK;
}

560
static HRESULT WINAPI IPersistFile_fnGetCurFile(IPersistFile *iface, LPOLESTR *ppszFileName)
561
{
562
  IAVIFileImpl *This = impl_from_IPersistFile(iface);
563 564 565 566 567 568 569 570

  TRACE("(%p,%p)\n", iface, ppszFileName);

  if (ppszFileName == NULL)
    return AVIERR_BADPARAM;

  *ppszFileName = NULL;

571 572
  if (This->szFileName) {
    int len = lstrlenW(This->szFileName) + 1;
573

574
    *ppszFileName = CoTaskMemAlloc(len * sizeof(WCHAR));
575 576 577
    if (*ppszFileName == NULL)
      return AVIERR_MEMORY;

578
    strcpyW(*ppszFileName, This->szFileName);
579 580 581 582 583
  }

  return AVIERR_OK;
}

584 585 586 587 588 589 590 591 592 593 594 595
static const struct IPersistFileVtbl iwavpft = {
    IPersistFile_fnQueryInterface,
    IPersistFile_fnAddRef,
    IPersistFile_fnRelease,
    IPersistFile_fnGetClassID,
    IPersistFile_fnIsDirty,
    IPersistFile_fnLoad,
    IPersistFile_fnSave,
    IPersistFile_fnSaveCompleted,
    IPersistFile_fnGetCurFile
};

596 597
/***********************************************************************/

598
static inline IAVIFileImpl *impl_from_IAVIStream(IAVIStream *iface)
599
{
600 601
    return CONTAINING_RECORD(iface, IAVIFileImpl, IAVIStream_iface);
}
602

603 604 605
static HRESULT WINAPI IAVIStream_fnQueryInterface(IAVIStream *iface, REFIID riid, void **ret_iface)
{
    IAVIFileImpl *This = impl_from_IAVIStream(iface);
606

607
    return IUnknown_QueryInterface(This->outer_unk, riid, ret_iface);
608 609 610 611
}

static ULONG WINAPI IAVIStream_fnAddRef(IAVIStream *iface)
{
612
    IAVIFileImpl *This = impl_from_IAVIStream(iface);
613

614
    return IUnknown_AddRef(This->outer_unk);
615 616 617 618
}

static ULONG WINAPI IAVIStream_fnRelease(IAVIStream* iface)
{
619
    IAVIFileImpl *This = impl_from_IAVIStream(iface);
620

621
    return IUnknown_Release(This->outer_unk);
622 623 624 625 626 627 628 629 630 631 632
}

static HRESULT WINAPI IAVIStream_fnCreate(IAVIStream *iface, LPARAM lParam1,
					  LPARAM lParam2)
{
  TRACE("(%p,0x%08lX,0x%08lX)\n", iface, lParam1, lParam2);

  /* This IAVIStream interface needs an WAVFile */
  return AVIERR_UNSUPPORTED;
}

633
static HRESULT WINAPI IAVIStream_fnInfo(IAVIStream *iface, AVISTREAMINFOW *psi, LONG size)
634
{
635
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
636

637
  TRACE("(%p,%p,%d)\n", iface, psi, size);
638 639 640 641 642 643

  if (psi == NULL)
    return AVIERR_BADPARAM;
  if (size < 0)
    return AVIERR_BADSIZE;

644
  memcpy(psi, &This->sInfo, min((DWORD)size, sizeof(This->sInfo)));
645

646
  if ((DWORD)size < sizeof(This->sInfo))
647 648 649 650
    return AVIERR_BUFFERTOOSMALL;
  return AVIERR_OK;
}

651
static LONG WINAPI IAVIStream_fnFindSample(IAVIStream *iface, LONG pos, LONG flags)
652
{
653
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
654

655
  TRACE("(%p,%d,0x%08X)\n",iface,pos,flags);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677

  /* Do we have data? */
  if (This->lpFormat == NULL)
    return -1;

  /* We don't have an index */
  if (flags & FIND_INDEX)
    return -1;

  if (flags & FIND_FROM_START) {
    pos = This->sInfo.dwStart;
    flags &= ~(FIND_FROM_START|FIND_PREV);
    flags |= FIND_NEXT;
  }

  if (flags & FIND_FORMAT) {
    if ((flags & FIND_NEXT) && pos > 0)
      pos = -1;
    else
      pos = 0;
  }

678 679
  if ((flags & FIND_RET) == FIND_LENGTH ||
      (flags & FIND_RET) == FIND_SIZE)
680
    return This->sInfo.dwSampleSize;
681
  if ((flags & FIND_RET) == FIND_OFFSET)
682 683 684 685 686
    return This->ckData.dwDataOffset + pos * This->sInfo.dwSampleSize;

  return pos;
}

687 688
static HRESULT WINAPI IAVIStream_fnReadFormat(IAVIStream *iface, LONG pos, void *format,
        LONG *formatsize)
689
{
690
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
691

692
  TRACE("(%p,%d,%p,%p)\n", iface, pos, format, formatsize);
693 694 695 696 697 698

  if (formatsize == NULL)
    return AVIERR_BADPARAM;

  /* only interested in needed buffersize? */
  if (format == NULL || *formatsize <= 0) {
699
    *formatsize = This->cbFormat;
700 701 702 703 704

    return AVIERR_OK;
  }

  /* copy initial format (only as much as will fit) */
705 706 707
  memcpy(format, This->lpFormat, min(*formatsize, This->cbFormat));
  if (*formatsize < This->cbFormat) {
    *formatsize = This->cbFormat;
708 709 710
    return AVIERR_BUFFERTOOSMALL;
  }

711
  *formatsize = This->cbFormat;
712 713 714
  return AVIERR_OK;
}

715 716
static HRESULT WINAPI IAVIStream_fnSetFormat(IAVIStream *iface, LONG pos, void *format,
        LONG formatsize)
717
{
718
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
719

720
  TRACE("(%p,%d,%p,%d)\n", iface, pos, format, formatsize);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

  /* check parameters */
  if (format == NULL || formatsize <= sizeof(PCMWAVEFORMAT))
    return AVIERR_BADPARAM;

  /* We can only do this to an empty wave file, but ignore call
   * if still same format */
  if (This->lpFormat != NULL) {
    if (formatsize != This->cbFormat ||
	memcmp(format, This->lpFormat, formatsize) != 0)
      return AVIERR_UNSUPPORTED;

    return AVIERR_OK;
  }

  /* only support start at position 0 */
  if (pos != 0)
    return AVIERR_UNSUPPORTED;

  /* Do we have write permission? */
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

  /* get memory for format and copy it */
745
  This->lpFormat = HeapAlloc(GetProcessHeap(), 0, formatsize);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  if (This->lpFormat == NULL)
    return AVIERR_MEMORY;

  This->cbFormat = formatsize;
  memcpy(This->lpFormat, format, formatsize);

  /* update info's about 'data' chunk */
  This->ckData.dwDataOffset = formatsize + 7 * sizeof(DWORD);
  This->ckData.cksize       = 0;

  /* for non-pcm format we need also a 'fact' chunk */
  if (This->lpFormat->wFormatTag != WAVE_FORMAT_PCM)
    This->ckData.dwDataOffset += 3 * sizeof(DWORD);

  /* update stream and file info */
  This->sInfo.dwSampleSize = This->lpFormat->nBlockAlign;
  This->sInfo.dwScale      = This->lpFormat->nBlockAlign;
  This->sInfo.dwRate       = This->lpFormat->nAvgBytesPerSec;
  This->sInfo.dwLength     = 0;
  This->sInfo.dwSuggestedBufferSize = 0;

  return AVIERR_OK;
}

770 771
static HRESULT WINAPI IAVIStream_fnRead(IAVIStream *iface, LONG start, LONG samples, void *buffer,
        LONG buffersize, LONG *bytesread, LONG *samplesread)
772
{
773
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
774

775
  TRACE("(%p,%d,%d,%p,%d,%p,%p)\n", iface, start, samples, buffer,
776 777 778 779 780 781 782 783 784
	buffersize, bytesread, samplesread);

  /* clear return parameters if given */
  if (bytesread != NULL)
    *bytesread = 0;
  if (samplesread != NULL)
    *samplesread = 0;

  /* positions without data */
785
  if (start < 0 || (DWORD)start > This->sInfo.dwLength)
786 787 788 789 790 791 792
    return AVIERR_OK;

  /* check samples */
  if (samples < 0)
    samples = 0;
  if (buffersize > 0) {
    if (samples > 0)
793
      samples = min((DWORD)samples, buffersize / This->sInfo.dwSampleSize);
794 795 796 797 798
    else
      samples = buffersize / This->sInfo.dwSampleSize;
  }

  /* limit to end of stream */
799
  if ((DWORD)(start + samples) > This->sInfo.dwLength)
800 801 802 803
    samples = This->sInfo.dwLength - start;

  /* request only the sizes? */
  if (buffer == NULL || buffersize <= 0) {
804
    /* then I need at least one parameter for it */
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    if (bytesread == NULL && samplesread == NULL)
      return AVIERR_BADPARAM;

    if (bytesread != NULL)
      *bytesread = samples * This->sInfo.dwSampleSize;
    if (samplesread != NULL)
      *samplesread = samples;

    return AVIERR_OK;
  }

  /* nothing to read? */
  if (samples == 0)
    return AVIERR_OK;

820
  /* Can I read at least one sample? */
821
  if ((DWORD)buffersize < This->sInfo.dwSampleSize)
822 823 824 825 826 827 828
    return AVIERR_BUFFERTOOSMALL;

  buffersize = samples * This->sInfo.dwSampleSize;

  if (mmioSeek(This->hmmio, This->ckData.dwDataOffset
	       + start * This->sInfo.dwSampleSize, SEEK_SET) == -1)
    return AVIERR_FILEREAD;
829
  if (mmioRead(This->hmmio, buffer, buffersize) != buffersize)
830 831 832 833 834 835 836 837 838 839 840
    return AVIERR_FILEREAD;

  /* fill out return parameters if given */
  if (bytesread != NULL)
    *bytesread = buffersize;
  if (samplesread != NULL)
    *samplesread = samples;  

  return AVIERR_OK;
}

841 842
static HRESULT WINAPI IAVIStream_fnWrite(IAVIStream *iface, LONG start, LONG samples, void *buffer,
        LONG buffersize, DWORD flags, LONG *sampwritten, LONG *byteswritten)
843
{
844
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
845

846
  TRACE("(%p,%d,%d,%p,%d,0x%08X,%p,%p)\n", iface, start, samples,
847 848 849 850 851 852 853 854 855 856 857 858
	buffer, buffersize, flags, sampwritten, byteswritten);

  /* clear return parameters if given */
  if (sampwritten != NULL)
    *sampwritten = 0;
  if (byteswritten != NULL)
    *byteswritten = 0;

  /* check parameters */
  if (buffer == NULL && (buffersize > 0 || samples > 0))
    return AVIERR_BADPARAM;

859
  /* Do we have write permission? */
860 861 862 863 864 865 866 867 868 869 870
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

  /* < 0 means "append" */
  if (start < 0)
    start = This->sInfo.dwStart + This->sInfo.dwLength;

  /* check buffersize -- must multiple of samplesize */
  if (buffersize & ~(This->sInfo.dwSampleSize - 1))
    return AVIERR_BADSIZE;

871
  /* do we have anything to write? */
872
  if (buffer != NULL && buffersize > 0) {
873
    This->fDirty = TRUE;
874 875 876 877

    if (mmioSeek(This->hmmio, This->ckData.dwDataOffset +
		 start * This->sInfo.dwSampleSize, SEEK_SET) == -1)
      return AVIERR_FILEWRITE;
878
    if (mmioWrite(This->hmmio, buffer, buffersize) != buffersize)
879 880
      return AVIERR_FILEWRITE;

881
    This->sInfo.dwLength = max(This->sInfo.dwLength, (DWORD)start + samples);
882 883 884 885 886 887 888 889 890 891 892 893 894
    This->ckData.cksize  = max(This->ckData.cksize,
			       start * This->sInfo.dwSampleSize + buffersize);

    /* fill out return parameters if given */
    if (sampwritten != NULL)
      *sampwritten = samples;
    if (byteswritten != NULL)
      *byteswritten = buffersize;
  }

  return AVIERR_OK;
}

895
static HRESULT WINAPI IAVIStream_fnDelete(IAVIStream *iface, LONG start, LONG samples)
896
{
897
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
898

899
  TRACE("(%p,%d,%d)\n", iface, start, samples);
900 901 902 903 904 905

  /* check parameters */
  if (start < 0 || samples < 0)
    return AVIERR_BADPARAM;

  /* Delete before start of stream? */
906
  if ((DWORD)(start + samples) < This->sInfo.dwStart)
907 908 909
    return AVIERR_OK;

  /* Delete after end of stream? */
910
  if ((DWORD)start > This->sInfo.dwLength)
911 912 913 914 915 916
    return AVIERR_OK;

  /* For the rest we need write permissions */
  if ((This->uMode & MMIO_RWMODE) == 0)
    return AVIERR_READONLY;

917
  if ((DWORD)(start + samples) >= This->sInfo.dwLength) {
918 919 920 921
    /* deletion at end */
    samples = This->sInfo.dwLength - start;
    This->sInfo.dwLength -= samples;
    This->ckData.cksize  -= samples * This->sInfo.dwSampleSize;
922
  } else if ((DWORD)start <= This->sInfo.dwStart) {
923 924 925 926 927 928 929 930 931 932 933 934
    /* deletion at start */
    samples = This->sInfo.dwStart - start;
    start   = This->sInfo.dwStart;
    This->ckData.dwDataOffset += samples * This->sInfo.dwSampleSize;
    This->ckData.cksize       -= samples * This->sInfo.dwSampleSize;
  } else {
    /* deletion inside stream -- needs playlist and cue's */
    FIXME(": deletion inside of stream not supported!\n");

    return AVIERR_UNSUPPORTED;
  }

935
  This->fDirty = TRUE;
936 937 938 939

  return AVIERR_OK;
}

940
static HRESULT WINAPI IAVIStream_fnReadData(IAVIStream *iface, DWORD fcc, void *lp, LONG *lpread)
941
{
942
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
943

944
  return IAVIFile_ReadData(&This->IAVIFile_iface, fcc, lp, lpread);
945 946
}

947
static HRESULT WINAPI IAVIStream_fnWriteData(IAVIStream *iface, DWORD fcc, void *lp, LONG size)
948
{
949
  IAVIFileImpl *This = impl_from_IAVIStream(iface);
950

951
  return IAVIFile_WriteData(&This->IAVIFile_iface, fcc, lp, size);
952 953 954 955 956
}

static HRESULT WINAPI IAVIStream_fnSetInfo(IAVIStream *iface,
					   LPAVISTREAMINFOW info, LONG infolen)
{
957
  FIXME("(%p,%p,%d): stub\n", iface, info, infolen);
958 959 960 961

  return E_FAIL;
}

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
static const struct IAVIStreamVtbl iwavst = {
    IAVIStream_fnQueryInterface,
    IAVIStream_fnAddRef,
    IAVIStream_fnRelease,
    IAVIStream_fnCreate,
    IAVIStream_fnInfo,
    IAVIStream_fnFindSample,
    IAVIStream_fnReadFormat,
    IAVIStream_fnSetFormat,
    IAVIStream_fnRead,
    IAVIStream_fnWrite,
    IAVIStream_fnDelete,
    IAVIStream_fnReadData,
    IAVIStream_fnWriteData,
    IAVIStream_fnSetInfo
};

HRESULT AVIFILE_CreateWAVFile(IUnknown *outer_unk, REFIID riid, void **ret_iface)
{
    IAVIFileImpl *pfile;
    HRESULT hr;

    *ret_iface = NULL;

    pfile = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pfile));
    if (!pfile)
        return AVIERR_MEMORY;

    pfile->IUnknown_inner.lpVtbl = &unk_vtbl;
    pfile->IAVIFile_iface.lpVtbl = &iwavft;
    pfile->IPersistFile_iface.lpVtbl = &iwavpft;
    pfile->IAVIStream_iface.lpVtbl = &iwavst;
    pfile->ref = 1;
    if (outer_unk)
        pfile->outer_unk = outer_unk;
    else
        pfile->outer_unk = &pfile->IUnknown_inner;

    hr = IUnknown_QueryInterface(&pfile->IUnknown_inner, riid, ret_iface);
    IUnknown_Release(&pfile->IUnknown_inner);

    return hr;
}

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
/***********************************************************************/

static HRESULT AVIFILE_LoadFile(IAVIFileImpl *This)
{
  MMCKINFO ckRIFF;
  MMCKINFO ck;

  This->sInfo.dwLength = 0; /* just to be sure */
  This->fDirty = FALSE;

  /* search for RIFF chunk */
1017
  ckRIFF.fccType = 0; /* find any */
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  if (mmioDescend(This->hmmio, &ckRIFF, NULL, MMIO_FINDRIFF) != S_OK) {
    return AVIFILE_LoadSunFile(This);
  }

  if (ckRIFF.fccType != formtypeWAVE)
    return AVIERR_BADFORMAT;

  /* search WAVE format chunk */
  ck.ckid = ckidWAVEFORMAT;
  if (FindChunkAndKeepExtras(&This->extra, This->hmmio, &ck,
1028
			     &ckRIFF, MMIO_FINDCHUNK) != S_OK)
1029 1030 1031
    return AVIERR_FILEREAD;

  /* get memory for format and read it */
1032
  This->lpFormat = HeapAlloc(GetProcessHeap(), 0, ck.cksize);
1033 1034 1035 1036 1037 1038 1039 1040 1041
  if (This->lpFormat == NULL)
    return AVIERR_FILEREAD;
  This->cbFormat = ck.cksize;

  if (mmioRead(This->hmmio, (HPSTR)This->lpFormat, ck.cksize) != ck.cksize)
    return AVIERR_FILEREAD;
  if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
    return AVIERR_FILEREAD;

1042 1043 1044
  /* Non-pcm formats have a fact chunk.
   * We don't need it, so simply add it to the extra chunks.
   */
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

  /* find the big data chunk */
  This->ckData.ckid = ckidWAVEDATA;
  if (FindChunkAndKeepExtras(&This->extra, This->hmmio, &This->ckData,
			     &ckRIFF, MMIO_FINDCHUNK) != S_OK)
    return AVIERR_FILEREAD;

  memset(&This->sInfo, 0, sizeof(This->sInfo));
  This->sInfo.fccType      = streamtypeAUDIO;
  This->sInfo.dwRate       = This->lpFormat->nAvgBytesPerSec;
  This->sInfo.dwSampleSize =
    This->sInfo.dwScale    = This->lpFormat->nBlockAlign;
  This->sInfo.dwLength     = This->ckData.cksize / This->lpFormat->nBlockAlign;
  This->sInfo.dwSuggestedBufferSize = This->ckData.cksize;

1060 1061
  This->fInfo.dwStreams = 1;

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  if (mmioAscend(This->hmmio, &This->ckData, 0) != S_OK) {
    /* seems to be truncated */
    WARN(": file seems to be truncated!\n");
    This->ckData.cksize  = mmioSeek(This->hmmio, 0, SEEK_END) -
      This->ckData.dwDataOffset;
    This->sInfo.dwLength = This->ckData.cksize / This->lpFormat->nBlockAlign;
    This->sInfo.dwSuggestedBufferSize = This->ckData.cksize;
  }

  /* ignore errors */
  FindChunkAndKeepExtras(&This->extra, This->hmmio, &ck, &ckRIFF, 0);

  return AVIERR_OK;
}

static HRESULT AVIFILE_LoadSunFile(IAVIFileImpl *This)
{
1079
  SUNAUDIOHEADER auhdr;
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
  mmioSeek(This->hmmio, 0, SEEK_SET);
  if (mmioRead(This->hmmio, (HPSTR)&auhdr, sizeof(auhdr)) != sizeof(auhdr))
    return AVIERR_FILEREAD;

  if (auhdr.fccType == 0x0064732E) {
    /* header in little endian */
    This->ckData.dwDataOffset = LE2H_DWORD(auhdr.offset);
    This->ckData.cksize       = LE2H_DWORD(auhdr.size);

    auhdr.encoding   = LE2H_DWORD(auhdr.encoding);
    auhdr.sampleRate = LE2H_DWORD(auhdr.sampleRate);
    auhdr.channels   = LE2H_DWORD(auhdr.channels);
  } else if (auhdr.fccType == mmioFOURCC('.','s','n','d')) {
    /* header in big endian */
    This->ckData.dwDataOffset = BE2H_DWORD(auhdr.offset);
    This->ckData.cksize       = BE2H_DWORD(auhdr.size);

    auhdr.encoding   = BE2H_DWORD(auhdr.encoding);
    auhdr.sampleRate = BE2H_DWORD(auhdr.sampleRate);
    auhdr.channels   = BE2H_DWORD(auhdr.channels);
  } else
    return AVIERR_FILEREAD;

  if (auhdr.channels < 1)
    return AVIERR_BADFORMAT;

  /* get size of header */
  switch(auhdr.encoding) {
  case AU_ENCODING_ADPCM_G721_32:
    This->cbFormat = sizeof(G721_ADPCMWAVEFORMAT); break;
  case AU_ENCODING_ADPCM_G723_24:
    This->cbFormat = sizeof(G723_ADPCMWAVEFORMAT); break;
  case AU_ENCODING_ADPCM_G722:
  case AU_ENCODING_ADPCM_G723_5:
    WARN("unsupported Sun audio format %d\n", auhdr.encoding);
    return AVIERR_UNSUPPORTED; /* FIXME */
  default:
    This->cbFormat = sizeof(WAVEFORMATEX); break;
  };

1121
  This->lpFormat = HeapAlloc(GetProcessHeap(), 0, This->cbFormat);
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
  if (This->lpFormat == NULL)
    return AVIERR_MEMORY;

  This->lpFormat->nChannels      = auhdr.channels;
  This->lpFormat->nSamplesPerSec = auhdr.sampleRate;
  switch(auhdr.encoding) {
  case AU_ENCODING_ULAW_8:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_MULAW;
    This->lpFormat->wBitsPerSample = 8;
    break;
  case AU_ENCODING_PCM_8:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
    This->lpFormat->wBitsPerSample = 8;
    break;
  case AU_ENCODING_PCM_16:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
    This->lpFormat->wBitsPerSample = 16;
    break;
  case AU_ENCODING_PCM_24:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
    This->lpFormat->wBitsPerSample = 24;
    break;
  case AU_ENCODING_PCM_32:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
    This->lpFormat->wBitsPerSample = 32;
    break;
  case AU_ENCODING_ALAW_8:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_ALAW;
    This->lpFormat->wBitsPerSample = 8;
    break;
  case AU_ENCODING_ADPCM_G721_32:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_G721_ADPCM;
    This->lpFormat->wBitsPerSample = (3*5*8);
    This->lpFormat->nBlockAlign    = 15*15*8;
    This->lpFormat->cbSize         = sizeof(WORD);
    ((LPG721_ADPCMWAVEFORMAT)This->lpFormat)->nAuxBlockSize = 0;
    break;
  case AU_ENCODING_ADPCM_G723_24:
    This->lpFormat->wFormatTag     = WAVE_FORMAT_G723_ADPCM;
    This->lpFormat->wBitsPerSample = (3*5*8);
    This->lpFormat->nBlockAlign    = 15*15*8;
    This->lpFormat->cbSize         = 2*sizeof(WORD);
    ((LPG723_ADPCMWAVEFORMAT)This->lpFormat)->cbExtraSize   = 0;
    ((LPG723_ADPCMWAVEFORMAT)This->lpFormat)->nAuxBlockSize = 0;
    break;
  default:
    WARN("unsupported Sun audio format %d\n", auhdr.encoding);
    return AVIERR_UNSUPPORTED;
  };

  This->lpFormat->nBlockAlign =
    (This->lpFormat->nChannels * This->lpFormat->wBitsPerSample) / 8;
  if (This->lpFormat->nBlockAlign == 0 && This->lpFormat->wBitsPerSample < 8)
    This->lpFormat->nBlockAlign++;
  This->lpFormat->nAvgBytesPerSec =
    This->lpFormat->nBlockAlign * This->lpFormat->nSamplesPerSec;

1179
  This->fDirty = FALSE;
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

  This->sInfo.fccType               = streamtypeAUDIO;
  This->sInfo.fccHandler            = 0;
  This->sInfo.dwFlags               = 0;
  This->sInfo.wPriority             = 0;
  This->sInfo.wLanguage             = 0;
  This->sInfo.dwInitialFrames       = 0;
  This->sInfo.dwScale               = This->lpFormat->nBlockAlign;
  This->sInfo.dwRate                = This->lpFormat->nAvgBytesPerSec;
  This->sInfo.dwStart               = 0;
  This->sInfo.dwLength              =
    This->ckData.cksize / This->lpFormat->nBlockAlign;
  This->sInfo.dwSuggestedBufferSize = This->sInfo.dwLength;
  This->sInfo.dwSampleSize          = This->lpFormat->nBlockAlign;

  This->fInfo.dwStreams = 1;
  This->fInfo.dwScale   = 1;
  This->fInfo.dwRate    = This->lpFormat->nSamplesPerSec;
  This->fInfo.dwLength  =
    MulDiv(This->ckData.cksize, This->lpFormat->nSamplesPerSec,
	   This->lpFormat->nAvgBytesPerSec);

  return AVIERR_OK;
1203 1204
}

1205
static HRESULT AVIFILE_SaveFile(const IAVIFileImpl *This)
1206
{
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
  MMCKINFO ckRIFF;
  MMCKINFO ck;

  mmioSeek(This->hmmio, 0, SEEK_SET);

  /* create the RIFF chunk with formtype WAVE */
  ckRIFF.fccType = formtypeWAVE;
  ckRIFF.cksize  = 0;
  if (mmioCreateChunk(This->hmmio, &ckRIFF, MMIO_CREATERIFF) != S_OK)
    return AVIERR_FILEWRITE;

  /* the next chunk is the format */
  ck.ckid   = ckidWAVEFORMAT;
  ck.cksize = This->cbFormat;
  if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
    return AVIERR_FILEWRITE;
  if (This->lpFormat != NULL && This->cbFormat > 0) {
    if (mmioWrite(This->hmmio, (HPSTR)This->lpFormat, ck.cksize) != ck.cksize)
      return AVIERR_FILEWRITE;
  }
  if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
    return AVIERR_FILEWRITE;

  /* fact chunk is needed for non-pcm waveforms */
  if (This->lpFormat != NULL && This->cbFormat > sizeof(PCMWAVEFORMAT) &&
      This->lpFormat->wFormatTag != WAVE_FORMAT_PCM) {
    WAVEFORMATEX wfx;
    DWORD        dwFactLength;
    HACMSTREAM   has;

    /* try to open an appropriate audio codec to figure out
     * data for fact-chunk */
    wfx.wFormatTag = WAVE_FORMAT_PCM;
1240
    if (acmFormatSuggest(NULL, This->lpFormat, &wfx,
1241
			 sizeof(wfx), ACM_FORMATSUGGESTF_WFORMATTAG)) {
1242
      acmStreamOpen(&has, NULL, This->lpFormat, &wfx, NULL,
1243 1244 1245 1246 1247 1248
		    0, 0, ACM_STREAMOPENF_NONREALTIME);
      acmStreamSize(has, This->ckData.cksize, &dwFactLength,
		    ACM_STREAMSIZEF_SOURCE);
      dwFactLength /= wfx.nBlockAlign;
      acmStreamClose(has, 0);

1249
      /* create the fact chunk */
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
      ck.ckid   = ckidWAVEFACT;
      ck.cksize = sizeof(dwFactLength);

      /* test for enough space before data chunk */
      if (mmioSeek(This->hmmio, 0, SEEK_CUR) > This->ckData.dwDataOffset
	  - ck.cksize - 4 * sizeof(DWORD))
	return AVIERR_FILEWRITE;
      if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
	return AVIERR_FILEWRITE;
      if (mmioWrite(This->hmmio, (HPSTR)&dwFactLength, ck.cksize) != ck.cksize)
	return AVIERR_FILEWRITE;
      if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
	return AVIERR_FILEWRITE;
    } else
      ERR(": fact chunk is needed for non-pcm files -- currently no codec found, so skipped!\n");
  }

1267
  /* if there was extra stuff, we need to fill it with JUNK */
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
  if (mmioSeek(This->hmmio, 0, SEEK_CUR) + 2 * sizeof(DWORD) < This->ckData.dwDataOffset) {
    ck.ckid   = ckidAVIPADDING;
    ck.cksize = 0;
    if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
      return AVIERR_FILEWRITE;

    if (mmioSeek(This->hmmio, This->ckData.dwDataOffset
		 - 2 * sizeof(DWORD), SEEK_SET) == -1)
      return AVIERR_FILEWRITE;
    if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
      return AVIERR_FILEWRITE;
  }

1281
  /* create the data chunk */
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
  ck.ckid   = ckidWAVEDATA;
  ck.cksize = This->ckData.cksize;
  if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
    return AVIERR_FILEWRITE;
  if (mmioSeek(This->hmmio, This->ckData.cksize, SEEK_CUR) == -1)
    return AVIERR_FILEWRITE;
  if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
    return AVIERR_FILEWRITE;

  /* some optional extra chunks? */
  if (This->extra.lp != NULL && This->extra.cb > 0) {
    /* chunk headers are already in structure */
    if (mmioWrite(This->hmmio, This->extra.lp, This->extra.cb) != This->extra.cb)
      return AVIERR_FILEWRITE;
  }

  /* close RIFF chunk */
  if (mmioAscend(This->hmmio, &ckRIFF, 0) != S_OK)
    return AVIERR_FILEWRITE;
  if (mmioFlush(This->hmmio, 0) != S_OK)
    return AVIERR_FILEWRITE;

  return AVIERR_OK;
1305
}