Add a '\r\n' to lpszHeaders if it is not already terminated by
[wine] / dlls / avifil32 / wavfile.c
1 /*
2  * Copyright 2002 Michael Günnewig
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #define COM_NO_WINDOWS_H
20 #include <assert.h>
21 #include <stdarg.h>
22
23 #include "windef.h"
24 #include "winbase.h"
25 #include "wingdi.h"
26 #include "winuser.h"
27 #include "winnls.h"
28 #include "winerror.h"
29 #include "windowsx.h"
30 #include "mmsystem.h"
31 #include "vfw.h"
32 #include "msacm.h"
33
34 #include "avifile_private.h"
35 #include "extrachunk.h"
36
37 #include "wine/debug.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(avifile);
40
41 /***********************************************************************/
42
43 #define formtypeWAVE    mmioFOURCC('W','A','V','E')
44 #define ckidWAVEFORMAT  mmioFOURCC('f','m','t',' ')
45 #define ckidWAVEFACT    mmioFOURCC('f','a','c','t')
46 #define ckidWAVEDATA    mmioFOURCC('d','a','t','a')
47
48 /***********************************************************************/
49
50 #define ENDIAN_SWAPWORD(x)  ((((x) >> 8) & 0xFF) | (((x) & 0xFF) << 8))
51 #define ENDIAN_SWAPDWORD(x) (ENDIAN_SWAPWORD((x >> 16) & 0xFFFF) | \
52                              ENDIAN_SWAPWORD(x & 0xFFFF) << 16)
53
54 #ifdef WORDS_BIGENDIAN
55 #define BE2H_WORD(x)  (x)
56 #define BE2H_DWORD(x) (x)
57 #define LE2H_WORD(x)  ENDIAN_SWAPWORD(x)
58 #define LE2H_DWORD(x) ENDIAN_SWAPDWORD(x)
59 #else
60 #define BE2H_WORD(x)  ENDIAN_SWAPWORD(x)
61 #define BE2H_DWORD(x) ENDIAN_SWAPDWORD(x)
62 #define LE2H_WORD(x)  (x)
63 #define LE2H_DWORD(x) (x)
64 #endif
65
66 typedef struct {
67   FOURCC  fccType;
68   DWORD   offset;
69   DWORD   size;
70   INT     encoding;
71   DWORD   sampleRate;
72   DWORD   channels;
73 } SUNAUDIOHEADER;
74
75 #define AU_ENCODING_ULAW_8                 1
76 #define AU_ENCODING_PCM_8                  2
77 #define AU_ENCODING_PCM_16                 3
78 #define AU_ENCODING_PCM_24                 4
79 #define AU_ENCODING_PCM_32                 5
80 #define AU_ENCODING_FLOAT                  6
81 #define AU_ENCODING_DOUBLE                 7
82 #define AU_ENCODING_ADPCM_G721_32         23
83 #define AU_ENCODING_ADPCM_G722            24
84 #define AU_ENCODING_ADPCM_G723_24         25
85 #define AU_ENCODING_ADPCM_G723_5          26
86 #define AU_ENCODING_ALAW_8                27
87
88 /***********************************************************************/
89
90 static HRESULT WINAPI IAVIFile_fnQueryInterface(IAVIFile* iface,REFIID refiid,LPVOID *obj);
91 static ULONG   WINAPI IAVIFile_fnAddRef(IAVIFile* iface);
92 static ULONG   WINAPI IAVIFile_fnRelease(IAVIFile* iface);
93 static HRESULT WINAPI IAVIFile_fnInfo(IAVIFile*iface,AVIFILEINFOW*afi,LONG size);
94 static HRESULT WINAPI IAVIFile_fnGetStream(IAVIFile*iface,PAVISTREAM*avis,DWORD fccType,LONG lParam);
95 static HRESULT WINAPI IAVIFile_fnCreateStream(IAVIFile*iface,PAVISTREAM*avis,AVISTREAMINFOW*asi);
96 static HRESULT WINAPI IAVIFile_fnWriteData(IAVIFile*iface,DWORD ckid,LPVOID lpData,LONG size);
97 static HRESULT WINAPI IAVIFile_fnReadData(IAVIFile*iface,DWORD ckid,LPVOID lpData,LONG *size);
98 static HRESULT WINAPI IAVIFile_fnEndRecord(IAVIFile*iface);
99 static HRESULT WINAPI IAVIFile_fnDeleteStream(IAVIFile*iface,DWORD fccType,LONG lParam);
100
101 struct ICOM_VTABLE(IAVIFile) iwavft = {
102   ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
103   IAVIFile_fnQueryInterface,
104   IAVIFile_fnAddRef,
105   IAVIFile_fnRelease,
106   IAVIFile_fnInfo,
107   IAVIFile_fnGetStream,
108   IAVIFile_fnCreateStream,
109   IAVIFile_fnWriteData,
110   IAVIFile_fnReadData,
111   IAVIFile_fnEndRecord,
112   IAVIFile_fnDeleteStream
113 };
114
115 static HRESULT WINAPI IPersistFile_fnQueryInterface(IPersistFile*iface,REFIID refiid,LPVOID*obj);
116 static ULONG   WINAPI IPersistFile_fnAddRef(IPersistFile*iface);
117 static ULONG   WINAPI IPersistFile_fnRelease(IPersistFile*iface);
118 static HRESULT WINAPI IPersistFile_fnGetClassID(IPersistFile*iface,CLSID*pClassID);
119 static HRESULT WINAPI IPersistFile_fnIsDirty(IPersistFile*iface);
120 static HRESULT WINAPI IPersistFile_fnLoad(IPersistFile*iface,LPCOLESTR pszFileName,DWORD dwMode);
121 static HRESULT WINAPI IPersistFile_fnSave(IPersistFile*iface,LPCOLESTR pszFileName,BOOL fRemember);
122 static HRESULT WINAPI IPersistFile_fnSaveCompleted(IPersistFile*iface,LPCOLESTR pszFileName);
123 static HRESULT WINAPI IPersistFile_fnGetCurFile(IPersistFile*iface,LPOLESTR*ppszFileName);
124
125 struct ICOM_VTABLE(IPersistFile) iwavpft = {
126   ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
127   IPersistFile_fnQueryInterface,
128   IPersistFile_fnAddRef,
129   IPersistFile_fnRelease,
130   IPersistFile_fnGetClassID,
131   IPersistFile_fnIsDirty,
132   IPersistFile_fnLoad,
133   IPersistFile_fnSave,
134   IPersistFile_fnSaveCompleted,
135   IPersistFile_fnGetCurFile
136 };
137
138 static HRESULT WINAPI IAVIStream_fnQueryInterface(IAVIStream*iface,REFIID refiid,LPVOID *obj);
139 static ULONG   WINAPI IAVIStream_fnAddRef(IAVIStream*iface);
140 static ULONG   WINAPI IAVIStream_fnRelease(IAVIStream* iface);
141 static HRESULT WINAPI IAVIStream_fnCreate(IAVIStream*iface,LPARAM lParam1,LPARAM lParam2);
142 static HRESULT WINAPI IAVIStream_fnInfo(IAVIStream*iface,AVISTREAMINFOW *psi,LONG size);
143 static LONG    WINAPI IAVIStream_fnFindSample(IAVIStream*iface,LONG pos,LONG flags);
144 static HRESULT WINAPI IAVIStream_fnReadFormat(IAVIStream*iface,LONG pos,LPVOID format,LONG *formatsize);
145 static HRESULT WINAPI IAVIStream_fnSetFormat(IAVIStream*iface,LONG pos,LPVOID format,LONG formatsize);
146 static HRESULT WINAPI IAVIStream_fnRead(IAVIStream*iface,LONG start,LONG samples,LPVOID buffer,LONG buffersize,LONG *bytesread,LONG *samplesread);
147 static HRESULT WINAPI IAVIStream_fnWrite(IAVIStream*iface,LONG start,LONG samples,LPVOID buffer,LONG buffersize,DWORD flags,LONG *sampwritten,LONG *byteswritten);
148 static HRESULT WINAPI IAVIStream_fnDelete(IAVIStream*iface,LONG start,LONG samples);
149 static HRESULT WINAPI IAVIStream_fnReadData(IAVIStream*iface,DWORD fcc,LPVOID lp,LONG *lpread);
150 static HRESULT WINAPI IAVIStream_fnWriteData(IAVIStream*iface,DWORD fcc,LPVOID lp,LONG size);
151 static HRESULT WINAPI IAVIStream_fnSetInfo(IAVIStream*iface,AVISTREAMINFOW*info,LONG infolen);
152
153 struct ICOM_VTABLE(IAVIStream) iwavst = {
154   ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
155   IAVIStream_fnQueryInterface,
156   IAVIStream_fnAddRef,
157   IAVIStream_fnRelease,
158   IAVIStream_fnCreate,
159   IAVIStream_fnInfo,
160   IAVIStream_fnFindSample,
161   IAVIStream_fnReadFormat,
162   IAVIStream_fnSetFormat,
163   IAVIStream_fnRead,
164   IAVIStream_fnWrite,
165   IAVIStream_fnDelete,
166   IAVIStream_fnReadData,
167   IAVIStream_fnWriteData,
168   IAVIStream_fnSetInfo
169 };
170
171 typedef struct _IAVIFileImpl IAVIFileImpl;
172
173 typedef struct _IPersistFileImpl {
174   /* IUnknown stuff */
175   ICOM_VFIELD(IPersistFile);
176
177   /* IPersistFile stuff */
178   IAVIFileImpl     *paf;
179 } IPersistFileImpl;
180
181 typedef struct _IAVIStreamImpl {
182   /* IUnknown stuff */
183   ICOM_VFIELD(IAVIStream);
184
185   /* IAVIStream stuff */
186   IAVIFileImpl     *paf;
187 } IAVIStreamImpl;
188
189 struct _IAVIFileImpl {
190   /* IUnknown stuff */
191   ICOM_VFIELD(IAVIFile);
192   DWORD             ref;
193
194   /* IAVIFile, IAVIStream stuff... */
195   IPersistFileImpl  iPersistFile;
196   IAVIStreamImpl    iAVIStream;
197
198   AVIFILEINFOW      fInfo;
199   AVISTREAMINFOW    sInfo;
200
201   LPWAVEFORMATEX    lpFormat;
202   LONG              cbFormat;
203
204   MMCKINFO          ckData;
205
206   EXTRACHUNKS       extra;
207
208   /* IPersistFile stuff ... */
209   HMMIO             hmmio;
210   LPWSTR            szFileName;
211   UINT              uMode;
212   BOOL              fDirty;
213 };
214
215 /***********************************************************************/
216
217 static HRESULT AVIFILE_LoadFile(IAVIFileImpl *This);
218 static HRESULT AVIFILE_LoadSunFile(IAVIFileImpl *This);
219 static HRESULT AVIFILE_SaveFile(IAVIFileImpl *This);
220
221 HRESULT AVIFILE_CreateWAVFile(REFIID riid, LPVOID *ppv)
222 {
223   IAVIFileImpl *pfile;
224   HRESULT       hr;
225
226   assert(riid != NULL && ppv != NULL);
227
228   *ppv = NULL;
229
230   pfile = (IAVIFileImpl*)LocalAlloc(LPTR, sizeof(IAVIFileImpl));
231   if (pfile == NULL)
232     return AVIERR_MEMORY;
233
234   pfile->lpVtbl                = &iwavft;
235   pfile->iPersistFile.lpVtbl   = &iwavpft;
236   pfile->iAVIStream.lpVtbl     = &iwavst;
237   pfile->ref = 0;
238   pfile->iPersistFile.paf = pfile;
239   pfile->iAVIStream.paf   = pfile;
240
241   hr = IUnknown_QueryInterface((IUnknown*)pfile, riid, ppv);
242   if (FAILED(hr))
243     LocalFree((HLOCAL)pfile);
244
245   return hr;
246 }
247
248 static HRESULT WINAPI IAVIFile_fnQueryInterface(IAVIFile *iface, REFIID refiid,
249                                                 LPVOID *obj)
250 {
251   ICOM_THIS(IAVIFileImpl,iface);
252
253   TRACE("(%p,%s,%p)\n", This, debugstr_guid(refiid), obj);
254
255   if (IsEqualGUID(&IID_IUnknown, refiid) ||
256       IsEqualGUID(&IID_IAVIFile, refiid)) {
257     *obj = iface;
258     return S_OK;
259   } else if (This->fInfo.dwStreams == 1 &&
260              IsEqualGUID(&IID_IAVIStream, refiid)) {
261     *obj = &This->iAVIStream;
262     return S_OK;
263   } else if (IsEqualGUID(&IID_IPersistFile, refiid)) {
264     *obj = &This->iPersistFile;
265     return S_OK;
266   }
267
268   return OLE_E_ENUM_NOMORE;
269 }
270
271 static ULONG WINAPI IAVIFile_fnAddRef(IAVIFile *iface)
272 {
273   ICOM_THIS(IAVIFileImpl,iface);
274
275   TRACE("(%p)\n",iface);
276
277   return ++(This->ref);
278 }
279
280 static ULONG WINAPI IAVIFile_fnRelease(IAVIFile *iface)
281 {
282   ICOM_THIS(IAVIFileImpl,iface);
283
284   TRACE("(%p)\n",iface);
285
286   if (!--(This->ref)) {
287     if (This->fDirty) {
288       /* need to write headers to file */
289       AVIFILE_SaveFile(This);
290     }
291
292     if (This->lpFormat != NULL) {
293       GlobalFreePtr(This->lpFormat);
294       This->lpFormat = NULL;
295       This->cbFormat = 0;
296     }
297     if (This->extra.lp != NULL) {
298       GlobalFreePtr(This->extra.lp);
299       This->extra.lp = NULL;
300       This->extra.cb = 0;
301     }
302     if (This->szFileName != NULL) {
303       LocalFree((HLOCAL)This->szFileName);
304       This->szFileName = NULL;
305     }
306     if (This->hmmio != NULL) {
307       mmioClose(This->hmmio, 0);
308       This->hmmio = NULL;
309     }
310
311     LocalFree((HLOCAL)This);
312     return 0;
313   }
314   return This->ref;
315 }
316
317 static HRESULT WINAPI IAVIFile_fnInfo(IAVIFile *iface, LPAVIFILEINFOW afi,
318                                       LONG size)
319 {
320   ICOM_THIS(IAVIFileImpl,iface);
321
322   TRACE("(%p,%p,%ld)\n",iface,afi,size);
323
324   if (afi == NULL)
325     return AVIERR_BADPARAM;
326   if (size < 0)
327     return AVIERR_BADSIZE;
328
329   /* update file info */
330   This->fInfo.dwFlags = 0;
331   This->fInfo.dwCaps  = AVIFILECAPS_CANREAD|AVIFILECAPS_CANWRITE;
332   if (This->lpFormat != NULL) {
333     assert(This->sInfo.dwScale != 0);
334
335     This->fInfo.dwStreams             = 1;
336     This->fInfo.dwScale               = This->sInfo.dwScale;
337     This->fInfo.dwRate                = This->sInfo.dwRate;
338     This->fInfo.dwLength              = This->sInfo.dwLength;
339     This->fInfo.dwSuggestedBufferSize = This->ckData.cksize;
340     This->fInfo.dwMaxBytesPerSec =
341       MulDiv(This->sInfo.dwSampleSize,This->sInfo.dwRate,This->sInfo.dwScale);
342   }
343
344   memcpy(afi, &This->fInfo, min((DWORD)size, sizeof(This->fInfo)));
345
346   if ((DWORD)size < sizeof(This->fInfo))
347     return AVIERR_BUFFERTOOSMALL;
348   return AVIERR_OK;
349 }
350
351 static HRESULT WINAPI IAVIFile_fnGetStream(IAVIFile *iface, PAVISTREAM *avis,
352                                            DWORD fccType, LONG lParam)
353 {
354   ICOM_THIS(IAVIFileImpl,iface);
355
356   TRACE("(%p,%p,0x%08lX,%ld)\n", iface, avis, fccType, lParam);
357
358   /* check parameter */
359   if (avis == NULL)
360     return AVIERR_BADPARAM;
361
362   *avis = NULL;
363
364   /* Does our stream exists? */
365   if (lParam != 0 || This->fInfo.dwStreams == 0)
366     return AVIERR_NODATA;
367   if (fccType != 0 && fccType != streamtypeAUDIO)
368     return AVIERR_NODATA;
369
370   *avis = (PAVISTREAM)&This->iAVIStream;
371   IAVIFile_AddRef(iface);
372
373   return AVIERR_OK;
374 }
375
376 static HRESULT WINAPI IAVIFile_fnCreateStream(IAVIFile *iface,PAVISTREAM *avis,
377                                               LPAVISTREAMINFOW asi)
378 {
379   ICOM_THIS(IAVIFileImpl,iface);
380
381   TRACE("(%p,%p,%p)\n", iface, avis, asi);
382
383   /* check parameters */
384   if (avis == NULL || asi == NULL)
385     return AVIERR_BADPARAM;
386
387   *avis = NULL;
388
389   /* We only support one audio stream */
390   if (This->fInfo.dwStreams != 0 || This->lpFormat != NULL)
391     return AVIERR_UNSUPPORTED;
392   if (asi->fccType != streamtypeAUDIO)
393     return AVIERR_UNSUPPORTED;
394
395   /* Does the user have write permission? */
396   if ((This->uMode & MMIO_RWMODE) == 0)
397     return AVIERR_READONLY;
398
399   This->cbFormat = 0;
400   This->lpFormat = NULL;
401
402   memcpy(&This->sInfo, asi, sizeof(This->sInfo));
403
404   /* make sure streaminfo if okay for us */
405   This->sInfo.fccHandler          = 0;
406   This->sInfo.dwFlags             = 0;
407   This->sInfo.dwCaps              = AVIFILECAPS_CANREAD|AVIFILECAPS_CANWRITE;
408   This->sInfo.dwStart             = 0;
409   This->sInfo.dwInitialFrames     = 0;
410   This->sInfo.dwFormatChangeCount = 0;
411   memset(&This->sInfo.rcFrame, 0, sizeof(This->sInfo.rcFrame));
412
413   This->fInfo.dwStreams = 1;
414   This->fInfo.dwScale   = This->sInfo.dwScale;
415   This->fInfo.dwRate    = This->sInfo.dwRate;
416   This->fInfo.dwLength  = This->sInfo.dwLength;
417
418   This->ckData.dwDataOffset = 0;
419   This->ckData.cksize       = 0;
420
421   *avis = (PAVISTREAM)&This->iAVIStream;
422   IAVIFile_AddRef(iface);
423
424   return AVIERR_OK;
425 }
426
427 static HRESULT WINAPI IAVIFile_fnWriteData(IAVIFile *iface, DWORD ckid,
428                                            LPVOID lpData, LONG size)
429 {
430   ICOM_THIS(IAVIFileImpl,iface);
431
432   TRACE("(%p,0x%08lX,%p,%ld)\n", iface, ckid, lpData, size);
433
434   /* check parameters */
435   if (lpData == NULL)
436     return AVIERR_BADPARAM;
437   if (size < 0)
438     return AVIERR_BADSIZE;
439
440   /* Do we have write permission? */
441   if ((This->uMode & MMIO_RWMODE) == 0)
442     return AVIERR_READONLY;
443
444   This->fDirty = TRUE;
445
446   return WriteExtraChunk(&This->extra, ckid, lpData, size);
447 }
448
449 static HRESULT WINAPI IAVIFile_fnReadData(IAVIFile *iface, DWORD ckid,
450                                           LPVOID lpData, LONG *size)
451 {
452   ICOM_THIS(IAVIFileImpl,iface);
453
454   TRACE("(%p,0x%08lX,%p,%p)\n", iface, ckid, lpData, size);
455
456   return ReadExtraChunk(&This->extra, ckid, lpData, size);
457 }
458
459 static HRESULT WINAPI IAVIFile_fnEndRecord(IAVIFile *iface)
460 {
461   TRACE("(%p)\n",iface);
462
463   /* This is only needed for interleaved files.
464    * We have only one stream, which can't be interleaved.
465    */
466   return AVIERR_OK;
467 }
468
469 static HRESULT WINAPI IAVIFile_fnDeleteStream(IAVIFile *iface, DWORD fccType,
470                                               LONG lParam)
471 {
472   ICOM_THIS(IAVIFileImpl,iface);
473
474   TRACE("(%p,0x%08lX,%ld)\n", iface, fccType, lParam);
475
476   /* check parameter */
477   if (lParam < 0)
478     return AVIERR_BADPARAM;
479
480   /* Have we our audio stream? */
481   if (lParam != 0 || This->fInfo.dwStreams == 0 ||
482       (fccType != 0 && fccType != streamtypeAUDIO))
483     return AVIERR_NODATA;
484
485   /* Have user write permissions? */
486   if ((This->uMode & MMIO_RWMODE) == 0)
487     return AVIERR_READONLY;
488
489   GlobalFreePtr(This->lpFormat);
490   This->lpFormat = NULL;
491   This->cbFormat = 0;
492
493   /* update infos */
494   This->ckData.dwDataOffset = 0;
495   This->ckData.cksize       = 0;
496
497   This->sInfo.dwScale   = 0;
498   This->sInfo.dwRate    = 0;
499   This->sInfo.dwLength  = 0;
500   This->sInfo.dwSuggestedBufferSize = 0;
501
502   This->fInfo.dwStreams = 0;
503   This->fInfo.dwEditCount++;
504
505   This->fDirty = TRUE;
506
507   return AVIERR_OK;
508 }
509
510 /***********************************************************************/
511
512 static HRESULT WINAPI IPersistFile_fnQueryInterface(IPersistFile *iface,
513                                                     REFIID refiid, LPVOID *obj)
514 {
515   ICOM_THIS(IPersistFileImpl,iface);
516
517   assert(This->paf != NULL);
518
519   return IAVIFile_QueryInterface((PAVIFILE)This->paf, refiid, obj);
520 }
521
522 static ULONG   WINAPI IPersistFile_fnAddRef(IPersistFile *iface)
523 {
524   ICOM_THIS(IPersistFileImpl,iface);
525
526   assert(This->paf != NULL);
527
528   return IAVIFile_AddRef((PAVIFILE)This->paf);
529 }
530
531 static ULONG   WINAPI IPersistFile_fnRelease(IPersistFile *iface)
532 {
533   ICOM_THIS(IPersistFileImpl,iface);
534
535   assert(This->paf != NULL);
536
537   return IAVIFile_Release((PAVIFILE)This->paf);
538 }
539
540 static HRESULT WINAPI IPersistFile_fnGetClassID(IPersistFile *iface,
541                                                 LPCLSID pClassID)
542 {
543   TRACE("(%p,%p)\n", iface, pClassID);
544
545   if (pClassID == NULL)
546     return AVIERR_BADPARAM;
547
548   memcpy(pClassID, &CLSID_WAVFile, sizeof(CLSID_WAVFile));
549
550   return AVIERR_OK;
551 }
552
553 static HRESULT WINAPI IPersistFile_fnIsDirty(IPersistFile *iface)
554 {
555   ICOM_THIS(IPersistFileImpl,iface);
556
557   TRACE("(%p)\n", iface);
558
559   assert(This->paf != NULL);
560
561   return (This->paf->fDirty ? S_OK : S_FALSE);
562 }
563
564 static HRESULT WINAPI IPersistFile_fnLoad(IPersistFile *iface,
565                                           LPCOLESTR pszFileName, DWORD dwMode)
566 {
567   IAVIFileImpl *This = ((IPersistFileImpl*)iface)->paf;
568
569   WCHAR wszStreamFmt[50];
570   INT   len;
571
572   TRACE("(%p,%s,0x%08lX)\n", iface, debugstr_w(pszFileName), dwMode);
573
574   /* check parameter */
575   if (pszFileName == NULL)
576     return AVIERR_BADPARAM;
577
578   assert(This != NULL);
579   if (This->hmmio != NULL)
580     return AVIERR_ERROR; /* No reuse of this object for another file! */
581
582   /* remeber mode and name */
583   This->uMode = dwMode;
584
585   len = lstrlenW(pszFileName) + 1;
586   This->szFileName = (LPWSTR)LocalAlloc(LPTR, len * sizeof(WCHAR));
587   if (This->szFileName == NULL)
588     return AVIERR_MEMORY;
589   lstrcpyW(This->szFileName, pszFileName);
590
591   /* try to open the file */
592   This->hmmio = mmioOpenW(This->szFileName, NULL, MMIO_ALLOCBUF | dwMode);
593   if (This->hmmio == NULL) {
594     /* mmioOpenW not in native DLLs of Win9x -- try mmioOpenA */
595     LPSTR szFileName = LocalAlloc(LPTR, len * sizeof(CHAR));
596     if (szFileName == NULL)
597       return AVIERR_MEMORY;
598
599     WideCharToMultiByte(CP_ACP, 0, This->szFileName, -1, szFileName,
600                         len, NULL, NULL);
601
602     This->hmmio = mmioOpenA(szFileName, NULL, MMIO_ALLOCBUF | dwMode);
603     LocalFree((HLOCAL)szFileName);
604     if (This->hmmio == NULL)
605       return AVIERR_FILEOPEN;
606   }
607
608   memset(& This->fInfo, 0, sizeof(This->fInfo));
609   memset(& This->sInfo, 0, sizeof(This->sInfo));
610
611   LoadStringW(AVIFILE_hModule, IDS_WAVEFILETYPE, This->fInfo.szFileType,
612               sizeof(This->fInfo.szFileType));
613   if (LoadStringW(AVIFILE_hModule, IDS_WAVESTREAMFORMAT,
614                   wszStreamFmt, sizeof(wszStreamFmt)) > 0) {
615     wsprintfW(This->sInfo.szName, wszStreamFmt,
616               AVIFILE_BasenameW(This->szFileName));
617   }
618
619   /* should we create a new file? */
620   if (dwMode & OF_CREATE) {
621     /* nothing more to do */
622     return AVIERR_OK;
623   } else
624     return AVIFILE_LoadFile(This);
625 }
626
627 static HRESULT WINAPI IPersistFile_fnSave(IPersistFile *iface,
628                                           LPCOLESTR pszFileName,BOOL fRemember)
629 {
630   TRACE("(%p,%s,%d)\n", iface, debugstr_w(pszFileName), fRemember);
631
632   /* We write directly to disk, so nothing to do. */
633
634   return AVIERR_OK;
635 }
636
637 static HRESULT WINAPI IPersistFile_fnSaveCompleted(IPersistFile *iface,
638                                                    LPCOLESTR pszFileName)
639 {
640   TRACE("(%p,%s)\n", iface, debugstr_w(pszFileName));
641
642   /* We write directly to disk, so nothing to do. */
643
644   return AVIERR_OK;
645 }
646
647 static HRESULT WINAPI IPersistFile_fnGetCurFile(IPersistFile *iface,
648                                                 LPOLESTR *ppszFileName)
649 {
650   ICOM_THIS(IPersistFileImpl,iface);
651
652   TRACE("(%p,%p)\n", iface, ppszFileName);
653
654   if (ppszFileName == NULL)
655     return AVIERR_BADPARAM;
656
657   *ppszFileName = NULL;
658
659   assert(This->paf != NULL);
660
661   if (This->paf->szFileName != NULL) {
662     int len = lstrlenW(This->paf->szFileName);
663
664     *ppszFileName = (LPOLESTR)GlobalAllocPtr(GHND, len * sizeof(WCHAR));
665     if (*ppszFileName == NULL)
666       return AVIERR_MEMORY;
667
668     memcpy(*ppszFileName, This->paf->szFileName, len * sizeof(WCHAR));
669   }
670
671   return AVIERR_OK;
672 }
673
674 /***********************************************************************/
675
676 static HRESULT WINAPI IAVIStream_fnQueryInterface(IAVIStream *iface,
677                                                   REFIID refiid, LPVOID *obj)
678 {
679   ICOM_THIS(IAVIStreamImpl,iface);
680
681   assert(This->paf != NULL);
682
683   return IAVIFile_QueryInterface((PAVIFILE)This->paf, refiid, obj);
684 }
685
686 static ULONG WINAPI IAVIStream_fnAddRef(IAVIStream *iface)
687 {
688   ICOM_THIS(IAVIStreamImpl,iface);
689
690   assert(This->paf != NULL);
691
692   return IAVIFile_AddRef((PAVIFILE)This->paf);
693 }
694
695 static ULONG WINAPI IAVIStream_fnRelease(IAVIStream* iface)
696 {
697   ICOM_THIS(IAVIStreamImpl,iface);
698
699   assert(This->paf != NULL);
700
701   return IAVIFile_Release((PAVIFILE)This->paf);
702 }
703
704 static HRESULT WINAPI IAVIStream_fnCreate(IAVIStream *iface, LPARAM lParam1,
705                                           LPARAM lParam2)
706 {
707   TRACE("(%p,0x%08lX,0x%08lX)\n", iface, lParam1, lParam2);
708
709   /* This IAVIStream interface needs an WAVFile */
710   return AVIERR_UNSUPPORTED;
711 }
712
713 static HRESULT WINAPI IAVIStream_fnInfo(IAVIStream *iface,LPAVISTREAMINFOW psi,
714                                         LONG size)
715 {
716   ICOM_THIS(IAVIStreamImpl,iface);
717
718   TRACE("(%p,%p,%ld)\n", iface, psi, size);
719
720   if (psi == NULL)
721     return AVIERR_BADPARAM;
722   if (size < 0)
723     return AVIERR_BADSIZE;
724
725   memcpy(psi, &This->paf->sInfo, min((DWORD)size, sizeof(This->paf->sInfo)));
726
727   if ((DWORD)size < sizeof(This->paf->sInfo))
728     return AVIERR_BUFFERTOOSMALL;
729   return AVIERR_OK;
730 }
731
732 static LONG WINAPI IAVIStream_fnFindSample(IAVIStream *iface, LONG pos,
733                                            LONG flags)
734 {
735   IAVIFileImpl *This = ((IAVIStreamImpl*)iface)->paf;
736
737   TRACE("(%p,%ld,0x%08lX)\n",iface,pos,flags);
738
739   /* Do we have data? */
740   if (This->lpFormat == NULL)
741     return -1;
742
743   /* We don't have an index */
744   if (flags & FIND_INDEX)
745     return -1;
746
747   if (flags & FIND_FROM_START) {
748     pos = This->sInfo.dwStart;
749     flags &= ~(FIND_FROM_START|FIND_PREV);
750     flags |= FIND_NEXT;
751   }
752
753   if (flags & FIND_FORMAT) {
754     if ((flags & FIND_NEXT) && pos > 0)
755       pos = -1;
756     else
757       pos = 0;
758   }
759
760   if ((flags & FIND_RET) == FIND_LENGTH ||
761       (flags & FIND_RET) == FIND_SIZE)
762     return This->sInfo.dwSampleSize;
763   if ((flags & FIND_RET) == FIND_OFFSET)
764     return This->ckData.dwDataOffset + pos * This->sInfo.dwSampleSize;
765
766   return pos;
767 }
768
769 static HRESULT WINAPI IAVIStream_fnReadFormat(IAVIStream *iface, LONG pos,
770                                               LPVOID format, LONG *formatsize)
771 {
772   ICOM_THIS(IAVIStreamImpl,iface);
773
774   TRACE("(%p,%ld,%p,%p)\n", iface, pos, format, formatsize);
775
776   if (formatsize == NULL)
777     return AVIERR_BADPARAM;
778
779   /* only interested in needed buffersize? */
780   if (format == NULL || *formatsize <= 0) {
781     *formatsize = This->paf->cbFormat;
782
783     return AVIERR_OK;
784   }
785
786   /* copy initial format (only as much as will fit) */
787   memcpy(format, This->paf->lpFormat, min(*formatsize, This->paf->cbFormat));
788   if (*formatsize < This->paf->cbFormat) {
789     *formatsize = This->paf->cbFormat;
790     return AVIERR_BUFFERTOOSMALL;
791   }
792
793   *formatsize = This->paf->cbFormat;
794   return AVIERR_OK;
795 }
796
797 static HRESULT WINAPI IAVIStream_fnSetFormat(IAVIStream *iface, LONG pos,
798                                              LPVOID format, LONG formatsize)
799 {
800   IAVIFileImpl *This = ((IAVIStreamImpl*)iface)->paf;
801
802   TRACE("(%p,%ld,%p,%ld)\n", iface, pos, format, formatsize);
803
804   /* check parameters */
805   if (format == NULL || formatsize <= sizeof(PCMWAVEFORMAT))
806     return AVIERR_BADPARAM;
807
808   /* We can only do this to an empty wave file, but ignore call
809    * if still same format */
810   if (This->lpFormat != NULL) {
811     if (formatsize != This->cbFormat ||
812         memcmp(format, This->lpFormat, formatsize) != 0)
813       return AVIERR_UNSUPPORTED;
814
815     return AVIERR_OK;
816   }
817
818   /* only support start at position 0 */
819   if (pos != 0)
820     return AVIERR_UNSUPPORTED;
821
822   /* Do we have write permission? */
823   if ((This->uMode & MMIO_RWMODE) == 0)
824     return AVIERR_READONLY;
825
826   /* get memory for format and copy it */
827   This->lpFormat = (LPWAVEFORMATEX)GlobalAllocPtr(GMEM_MOVEABLE, formatsize);
828   if (This->lpFormat == NULL)
829     return AVIERR_MEMORY;
830
831   This->cbFormat = formatsize;
832   memcpy(This->lpFormat, format, formatsize);
833
834   /* update info's about 'data' chunk */
835   This->ckData.dwDataOffset = formatsize + 7 * sizeof(DWORD);
836   This->ckData.cksize       = 0;
837
838   /* for non-pcm format we need also a 'fact' chunk */
839   if (This->lpFormat->wFormatTag != WAVE_FORMAT_PCM)
840     This->ckData.dwDataOffset += 3 * sizeof(DWORD);
841
842   /* update stream and file info */
843   This->sInfo.dwSampleSize = This->lpFormat->nBlockAlign;
844   This->sInfo.dwScale      = This->lpFormat->nBlockAlign;
845   This->sInfo.dwRate       = This->lpFormat->nAvgBytesPerSec;
846   This->sInfo.dwLength     = 0;
847   This->sInfo.dwSuggestedBufferSize = 0;
848
849   return AVIERR_OK;
850 }
851
852 static HRESULT WINAPI IAVIStream_fnRead(IAVIStream *iface, LONG start,
853                                         LONG samples, LPVOID buffer,
854                                         LONG buffersize, LPLONG bytesread,
855                                         LPLONG samplesread)
856 {
857   IAVIFileImpl *This = ((IAVIStreamImpl*)iface)->paf;
858
859   TRACE("(%p,%ld,%ld,%p,%ld,%p,%p)\n", iface, start, samples, buffer,
860         buffersize, bytesread, samplesread);
861
862   /* clear return parameters if given */
863   if (bytesread != NULL)
864     *bytesread = 0;
865   if (samplesread != NULL)
866     *samplesread = 0;
867
868   /* positions without data */
869   if (start < 0 || (DWORD)start > This->sInfo.dwLength)
870     return AVIERR_OK;
871
872   /* check samples */
873   if (samples < 0)
874     samples = 0;
875   if (buffersize > 0) {
876     if (samples > 0)
877       samples = min((DWORD)samples, buffersize / This->sInfo.dwSampleSize);
878     else
879       samples = buffersize / This->sInfo.dwSampleSize;
880   }
881
882   /* limit to end of stream */
883   if ((DWORD)(start + samples) > This->sInfo.dwLength)
884     samples = This->sInfo.dwLength - start;
885
886   /* request only the sizes? */
887   if (buffer == NULL || buffersize <= 0) {
888     /* then I need atleast one parameter for it */
889     if (bytesread == NULL && samplesread == NULL)
890       return AVIERR_BADPARAM;
891
892     if (bytesread != NULL)
893       *bytesread = samples * This->sInfo.dwSampleSize;
894     if (samplesread != NULL)
895       *samplesread = samples;
896
897     return AVIERR_OK;
898   }
899
900   /* nothing to read? */
901   if (samples == 0)
902     return AVIERR_OK;
903
904   /* Can I atleast read one sample? */
905   if ((DWORD)buffersize < This->sInfo.dwSampleSize)
906     return AVIERR_BUFFERTOOSMALL;
907
908   buffersize = samples * This->sInfo.dwSampleSize;
909
910   if (mmioSeek(This->hmmio, This->ckData.dwDataOffset
911                + start * This->sInfo.dwSampleSize, SEEK_SET) == -1)
912     return AVIERR_FILEREAD;
913   if (mmioRead(This->hmmio, (HPSTR)buffer, buffersize) != buffersize)
914     return AVIERR_FILEREAD;
915
916   /* fill out return parameters if given */
917   if (bytesread != NULL)
918     *bytesread = buffersize;
919   if (samplesread != NULL)
920     *samplesread = samples;  
921
922   return AVIERR_OK;
923 }
924
925 static HRESULT WINAPI IAVIStream_fnWrite(IAVIStream *iface, LONG start,
926                                          LONG samples, LPVOID buffer,
927                                          LONG buffersize, DWORD flags,
928                                          LPLONG sampwritten,
929                                          LPLONG byteswritten)
930 {
931   IAVIFileImpl *This = ((IAVIStreamImpl*)iface)->paf;
932
933   TRACE("(%p,%ld,%ld,%p,%ld,0x%08lX,%p,%p)\n", iface, start, samples,
934         buffer, buffersize, flags, sampwritten, byteswritten);
935
936   /* clear return parameters if given */
937   if (sampwritten != NULL)
938     *sampwritten = 0;
939   if (byteswritten != NULL)
940     *byteswritten = 0;
941
942   /* check parameters */
943   if (buffer == NULL && (buffersize > 0 || samples > 0))
944     return AVIERR_BADPARAM;
945
946   /* Have we write permission? */
947   if ((This->uMode & MMIO_RWMODE) == 0)
948     return AVIERR_READONLY;
949
950   /* < 0 means "append" */
951   if (start < 0)
952     start = This->sInfo.dwStart + This->sInfo.dwLength;
953
954   /* check buffersize -- must multiple of samplesize */
955   if (buffersize & ~(This->sInfo.dwSampleSize - 1))
956     return AVIERR_BADSIZE;
957
958   /* have we anything to write? */
959   if (buffer != NULL && buffersize > 0) {
960     This->fDirty = 1;
961
962     if (mmioSeek(This->hmmio, This->ckData.dwDataOffset +
963                  start * This->sInfo.dwSampleSize, SEEK_SET) == -1)
964       return AVIERR_FILEWRITE;
965     if (mmioWrite(This->hmmio, (HPSTR)buffer, buffersize) != buffersize)
966       return AVIERR_FILEWRITE;
967
968     This->sInfo.dwLength = max(This->sInfo.dwLength, (DWORD)start + samples);
969     This->ckData.cksize  = max(This->ckData.cksize,
970                                start * This->sInfo.dwSampleSize + buffersize);
971
972     /* fill out return parameters if given */
973     if (sampwritten != NULL)
974       *sampwritten = samples;
975     if (byteswritten != NULL)
976       *byteswritten = buffersize;
977   }
978
979   return AVIERR_OK;
980 }
981
982 static HRESULT WINAPI IAVIStream_fnDelete(IAVIStream *iface, LONG start,
983                                           LONG samples)
984 {
985   IAVIFileImpl *This = ((IAVIStreamImpl*)iface)->paf;
986
987   TRACE("(%p,%ld,%ld)\n", iface, start, samples);
988
989   /* check parameters */
990   if (start < 0 || samples < 0)
991     return AVIERR_BADPARAM;
992
993   /* Delete before start of stream? */
994   if ((DWORD)(start + samples) < This->sInfo.dwStart)
995     return AVIERR_OK;
996
997   /* Delete after end of stream? */
998   if ((DWORD)start > This->sInfo.dwLength)
999     return AVIERR_OK;
1000
1001   /* For the rest we need write permissions */
1002   if ((This->uMode & MMIO_RWMODE) == 0)
1003     return AVIERR_READONLY;
1004
1005   if ((DWORD)(start + samples) >= This->sInfo.dwLength) {
1006     /* deletion at end */
1007     samples = This->sInfo.dwLength - start;
1008     This->sInfo.dwLength -= samples;
1009     This->ckData.cksize  -= samples * This->sInfo.dwSampleSize;
1010   } else if ((DWORD)start <= This->sInfo.dwStart) {
1011     /* deletion at start */
1012     samples = This->sInfo.dwStart - start;
1013     start   = This->sInfo.dwStart;
1014     This->ckData.dwDataOffset += samples * This->sInfo.dwSampleSize;
1015     This->ckData.cksize       -= samples * This->sInfo.dwSampleSize;
1016   } else {
1017     /* deletion inside stream -- needs playlist and cue's */
1018     FIXME(": deletion inside of stream not supported!\n");
1019
1020     return AVIERR_UNSUPPORTED;
1021   }
1022
1023   This->fDirty = 1;
1024
1025   return AVIERR_OK;
1026 }
1027
1028 static HRESULT WINAPI IAVIStream_fnReadData(IAVIStream *iface, DWORD fcc,
1029                                             LPVOID lp, LPLONG lpread)
1030 {
1031   ICOM_THIS(IAVIStreamImpl,iface);
1032
1033   assert(This->paf != NULL);
1034
1035   return IAVIFile_ReadData((PAVIFILE)This->paf, fcc, lp, lpread);
1036 }
1037
1038 static HRESULT WINAPI IAVIStream_fnWriteData(IAVIStream *iface, DWORD fcc,
1039                                              LPVOID lp, LONG size)
1040 {
1041   ICOM_THIS(IAVIStreamImpl,iface);
1042
1043   return IAVIFile_WriteData((PAVIFILE)This->paf, fcc, lp, size);
1044 }
1045
1046 static HRESULT WINAPI IAVIStream_fnSetInfo(IAVIStream *iface,
1047                                            LPAVISTREAMINFOW info, LONG infolen)
1048 {
1049   FIXME("(%p,%p,%ld): stub\n", iface, info, infolen);
1050
1051   return E_FAIL;
1052 }
1053
1054 /***********************************************************************/
1055
1056 static HRESULT AVIFILE_LoadFile(IAVIFileImpl *This)
1057 {
1058   MMCKINFO ckRIFF;
1059   MMCKINFO ck;
1060
1061   This->sInfo.dwLength = 0; /* just to be sure */
1062   This->fDirty = FALSE;
1063
1064   /* search for RIFF chunk */
1065   ckRIFF.fccType = 0; /* find any */
1066   if (mmioDescend(This->hmmio, &ckRIFF, NULL, MMIO_FINDRIFF) != S_OK) {
1067     return AVIFILE_LoadSunFile(This);
1068   }
1069
1070   if (ckRIFF.fccType != formtypeWAVE)
1071     return AVIERR_BADFORMAT;
1072
1073   /* search WAVE format chunk */
1074   ck.ckid = ckidWAVEFORMAT;
1075   if (FindChunkAndKeepExtras(&This->extra, This->hmmio, &ck,
1076                              &ckRIFF, MMIO_FINDCHUNK) != S_OK)
1077     return AVIERR_FILEREAD;
1078
1079   /* get memory for format and read it */
1080   This->lpFormat = (LPWAVEFORMATEX)GlobalAllocPtr(GMEM_MOVEABLE, ck.cksize);
1081   if (This->lpFormat == NULL)
1082     return AVIERR_FILEREAD;
1083   This->cbFormat = ck.cksize;
1084
1085   if (mmioRead(This->hmmio, (HPSTR)This->lpFormat, ck.cksize) != ck.cksize)
1086     return AVIERR_FILEREAD;
1087   if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
1088     return AVIERR_FILEREAD;
1089
1090   /* Non-pcm formats have a fact chunk.
1091    * We don't need it, so simply add it to the extra chunks.
1092    */
1093
1094   /* find the big data chunk */
1095   This->ckData.ckid = ckidWAVEDATA;
1096   if (FindChunkAndKeepExtras(&This->extra, This->hmmio, &This->ckData,
1097                              &ckRIFF, MMIO_FINDCHUNK) != S_OK)
1098     return AVIERR_FILEREAD;
1099
1100   memset(&This->sInfo, 0, sizeof(This->sInfo));
1101   This->sInfo.fccType      = streamtypeAUDIO;
1102   This->sInfo.dwRate       = This->lpFormat->nAvgBytesPerSec;
1103   This->sInfo.dwSampleSize =
1104     This->sInfo.dwScale    = This->lpFormat->nBlockAlign;
1105   This->sInfo.dwLength     = This->ckData.cksize / This->lpFormat->nBlockAlign;
1106   This->sInfo.dwSuggestedBufferSize = This->ckData.cksize;
1107
1108   This->fInfo.dwStreams = 1;
1109
1110   if (mmioAscend(This->hmmio, &This->ckData, 0) != S_OK) {
1111     /* seems to be truncated */
1112     WARN(": file seems to be truncated!\n");
1113     This->ckData.cksize  = mmioSeek(This->hmmio, 0, SEEK_END) -
1114       This->ckData.dwDataOffset;
1115     This->sInfo.dwLength = This->ckData.cksize / This->lpFormat->nBlockAlign;
1116     This->sInfo.dwSuggestedBufferSize = This->ckData.cksize;
1117   }
1118
1119   /* ignore errors */
1120   FindChunkAndKeepExtras(&This->extra, This->hmmio, &ck, &ckRIFF, 0);
1121
1122   return AVIERR_OK;
1123 }
1124
1125 static HRESULT AVIFILE_LoadSunFile(IAVIFileImpl *This)
1126 {
1127   SUNAUDIOHEADER auhdr;
1128
1129   mmioSeek(This->hmmio, 0, SEEK_SET);
1130   if (mmioRead(This->hmmio, (HPSTR)&auhdr, sizeof(auhdr)) != sizeof(auhdr))
1131     return AVIERR_FILEREAD;
1132
1133   if (auhdr.fccType == 0x0064732E) {
1134     /* header in little endian */
1135     This->ckData.dwDataOffset = LE2H_DWORD(auhdr.offset);
1136     This->ckData.cksize       = LE2H_DWORD(auhdr.size);
1137
1138     auhdr.encoding   = LE2H_DWORD(auhdr.encoding);
1139     auhdr.sampleRate = LE2H_DWORD(auhdr.sampleRate);
1140     auhdr.channels   = LE2H_DWORD(auhdr.channels);
1141   } else if (auhdr.fccType == mmioFOURCC('.','s','n','d')) {
1142     /* header in big endian */
1143     This->ckData.dwDataOffset = BE2H_DWORD(auhdr.offset);
1144     This->ckData.cksize       = BE2H_DWORD(auhdr.size);
1145
1146     auhdr.encoding   = BE2H_DWORD(auhdr.encoding);
1147     auhdr.sampleRate = BE2H_DWORD(auhdr.sampleRate);
1148     auhdr.channels   = BE2H_DWORD(auhdr.channels);
1149   } else
1150     return AVIERR_FILEREAD;
1151
1152   if (auhdr.channels < 1)
1153     return AVIERR_BADFORMAT;
1154
1155   /* get size of header */
1156   switch(auhdr.encoding) {
1157   case AU_ENCODING_ADPCM_G721_32:
1158     This->cbFormat = sizeof(G721_ADPCMWAVEFORMAT); break;
1159   case AU_ENCODING_ADPCM_G723_24:
1160     This->cbFormat = sizeof(G723_ADPCMWAVEFORMAT); break;
1161   case AU_ENCODING_ADPCM_G722:
1162   case AU_ENCODING_ADPCM_G723_5:
1163     WARN("unsupported Sun audio format %d\n", auhdr.encoding);
1164     return AVIERR_UNSUPPORTED; /* FIXME */
1165   default:
1166     This->cbFormat = sizeof(WAVEFORMATEX); break;
1167   };
1168
1169   This->lpFormat =
1170     (LPWAVEFORMATEX)GlobalAllocPtr(GMEM_MOVEABLE, This->cbFormat);
1171   if (This->lpFormat == NULL)
1172     return AVIERR_MEMORY;
1173
1174   This->lpFormat->nChannels      = auhdr.channels;
1175   This->lpFormat->nSamplesPerSec = auhdr.sampleRate;
1176   switch(auhdr.encoding) {
1177   case AU_ENCODING_ULAW_8:
1178     This->lpFormat->wFormatTag     = WAVE_FORMAT_MULAW;
1179     This->lpFormat->wBitsPerSample = 8;
1180     break;
1181   case AU_ENCODING_PCM_8:
1182     This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
1183     This->lpFormat->wBitsPerSample = 8;
1184     break;
1185   case AU_ENCODING_PCM_16:
1186     This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
1187     This->lpFormat->wBitsPerSample = 16;
1188     break;
1189   case AU_ENCODING_PCM_24:
1190     This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
1191     This->lpFormat->wBitsPerSample = 24;
1192     break;
1193   case AU_ENCODING_PCM_32:
1194     This->lpFormat->wFormatTag     = WAVE_FORMAT_PCM;
1195     This->lpFormat->wBitsPerSample = 32;
1196     break;
1197   case AU_ENCODING_ALAW_8:
1198     This->lpFormat->wFormatTag     = WAVE_FORMAT_ALAW;
1199     This->lpFormat->wBitsPerSample = 8;
1200     break;
1201   case AU_ENCODING_ADPCM_G721_32:
1202     This->lpFormat->wFormatTag     = WAVE_FORMAT_G721_ADPCM;
1203     This->lpFormat->wBitsPerSample = (3*5*8);
1204     This->lpFormat->nBlockAlign    = 15*15*8;
1205     This->lpFormat->cbSize         = sizeof(WORD);
1206     ((LPG721_ADPCMWAVEFORMAT)This->lpFormat)->nAuxBlockSize = 0;
1207     break;
1208   case AU_ENCODING_ADPCM_G723_24:
1209     This->lpFormat->wFormatTag     = WAVE_FORMAT_G723_ADPCM;
1210     This->lpFormat->wBitsPerSample = (3*5*8);
1211     This->lpFormat->nBlockAlign    = 15*15*8;
1212     This->lpFormat->cbSize         = 2*sizeof(WORD);
1213     ((LPG723_ADPCMWAVEFORMAT)This->lpFormat)->cbExtraSize   = 0;
1214     ((LPG723_ADPCMWAVEFORMAT)This->lpFormat)->nAuxBlockSize = 0;
1215     break;
1216   default:
1217     WARN("unsupported Sun audio format %d\n", auhdr.encoding);
1218     return AVIERR_UNSUPPORTED;
1219   };
1220
1221   This->lpFormat->nBlockAlign =
1222     (This->lpFormat->nChannels * This->lpFormat->wBitsPerSample) / 8;
1223   if (This->lpFormat->nBlockAlign == 0 && This->lpFormat->wBitsPerSample < 8)
1224     This->lpFormat->nBlockAlign++;
1225   This->lpFormat->nAvgBytesPerSec =
1226     This->lpFormat->nBlockAlign * This->lpFormat->nSamplesPerSec;
1227
1228   This->fDirty = 0;
1229
1230   This->sInfo.fccType               = streamtypeAUDIO;
1231   This->sInfo.fccHandler            = 0;
1232   This->sInfo.dwFlags               = 0;
1233   This->sInfo.wPriority             = 0;
1234   This->sInfo.wLanguage             = 0;
1235   This->sInfo.dwInitialFrames       = 0;
1236   This->sInfo.dwScale               = This->lpFormat->nBlockAlign;
1237   This->sInfo.dwRate                = This->lpFormat->nAvgBytesPerSec;
1238   This->sInfo.dwStart               = 0;
1239   This->sInfo.dwLength              =
1240     This->ckData.cksize / This->lpFormat->nBlockAlign;
1241   This->sInfo.dwSuggestedBufferSize = This->sInfo.dwLength;
1242   This->sInfo.dwSampleSize          = This->lpFormat->nBlockAlign;
1243
1244   This->fInfo.dwStreams = 1;
1245   This->fInfo.dwScale   = 1;
1246   This->fInfo.dwRate    = This->lpFormat->nSamplesPerSec;
1247   This->fInfo.dwLength  =
1248     MulDiv(This->ckData.cksize, This->lpFormat->nSamplesPerSec,
1249            This->lpFormat->nAvgBytesPerSec);
1250
1251   return AVIERR_OK;
1252 }
1253
1254 static HRESULT AVIFILE_SaveFile(IAVIFileImpl *This)
1255 {
1256   MMCKINFO ckRIFF;
1257   MMCKINFO ck;
1258
1259   mmioSeek(This->hmmio, 0, SEEK_SET);
1260
1261   /* create the RIFF chunk with formtype WAVE */
1262   ckRIFF.fccType = formtypeWAVE;
1263   ckRIFF.cksize  = 0;
1264   if (mmioCreateChunk(This->hmmio, &ckRIFF, MMIO_CREATERIFF) != S_OK)
1265     return AVIERR_FILEWRITE;
1266
1267   /* the next chunk is the format */
1268   ck.ckid   = ckidWAVEFORMAT;
1269   ck.cksize = This->cbFormat;
1270   if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
1271     return AVIERR_FILEWRITE;
1272   if (This->lpFormat != NULL && This->cbFormat > 0) {
1273     if (mmioWrite(This->hmmio, (HPSTR)This->lpFormat, ck.cksize) != ck.cksize)
1274       return AVIERR_FILEWRITE;
1275   }
1276   if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
1277     return AVIERR_FILEWRITE;
1278
1279   /* fact chunk is needed for non-pcm waveforms */
1280   if (This->lpFormat != NULL && This->cbFormat > sizeof(PCMWAVEFORMAT) &&
1281       This->lpFormat->wFormatTag != WAVE_FORMAT_PCM) {
1282     WAVEFORMATEX wfx;
1283     DWORD        dwFactLength;
1284     HACMSTREAM   has;
1285
1286     /* try to open an appropriate audio codec to figure out
1287      * data for fact-chunk */
1288     wfx.wFormatTag = WAVE_FORMAT_PCM;
1289     if (acmFormatSuggest(NULL, This->lpFormat, &wfx,
1290                          sizeof(wfx), ACM_FORMATSUGGESTF_WFORMATTAG)) {
1291       acmStreamOpen(&has, NULL, This->lpFormat, &wfx, NULL,
1292                     0, 0, ACM_STREAMOPENF_NONREALTIME);
1293       acmStreamSize(has, This->ckData.cksize, &dwFactLength,
1294                     ACM_STREAMSIZEF_SOURCE);
1295       dwFactLength /= wfx.nBlockAlign;
1296       acmStreamClose(has, 0);
1297
1298       /* crete the fact chunk */
1299       ck.ckid   = ckidWAVEFACT;
1300       ck.cksize = sizeof(dwFactLength);
1301
1302       /* test for enough space before data chunk */
1303       if (mmioSeek(This->hmmio, 0, SEEK_CUR) > This->ckData.dwDataOffset
1304           - ck.cksize - 4 * sizeof(DWORD))
1305         return AVIERR_FILEWRITE;
1306       if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
1307         return AVIERR_FILEWRITE;
1308       if (mmioWrite(This->hmmio, (HPSTR)&dwFactLength, ck.cksize) != ck.cksize)
1309         return AVIERR_FILEWRITE;
1310       if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
1311         return AVIERR_FILEWRITE;
1312     } else
1313       ERR(": fact chunk is needed for non-pcm files -- currently no codec found, so skipped!\n");
1314   }
1315
1316   /* if here was extra stuff, we need to fill it with JUNK */
1317   if (mmioSeek(This->hmmio, 0, SEEK_CUR) + 2 * sizeof(DWORD) < This->ckData.dwDataOffset) {
1318     ck.ckid   = ckidAVIPADDING;
1319     ck.cksize = 0;
1320     if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
1321       return AVIERR_FILEWRITE;
1322
1323     if (mmioSeek(This->hmmio, This->ckData.dwDataOffset
1324                  - 2 * sizeof(DWORD), SEEK_SET) == -1)
1325       return AVIERR_FILEWRITE;
1326     if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
1327       return AVIERR_FILEWRITE;
1328   }
1329
1330   /* crete the data chunk */
1331   ck.ckid   = ckidWAVEDATA;
1332   ck.cksize = This->ckData.cksize;
1333   if (mmioCreateChunk(This->hmmio, &ck, 0) != S_OK)
1334     return AVIERR_FILEWRITE;
1335   if (mmioSeek(This->hmmio, This->ckData.cksize, SEEK_CUR) == -1)
1336     return AVIERR_FILEWRITE;
1337   if (mmioAscend(This->hmmio, &ck, 0) != S_OK)
1338     return AVIERR_FILEWRITE;
1339
1340   /* some optional extra chunks? */
1341   if (This->extra.lp != NULL && This->extra.cb > 0) {
1342     /* chunk headers are already in structure */
1343     if (mmioWrite(This->hmmio, This->extra.lp, This->extra.cb) != This->extra.cb)
1344       return AVIERR_FILEWRITE;
1345   }
1346
1347   /* close RIFF chunk */
1348   if (mmioAscend(This->hmmio, &ckRIFF, 0) != S_OK)
1349     return AVIERR_FILEWRITE;
1350   if (mmioFlush(This->hmmio, 0) != S_OK)
1351     return AVIERR_FILEWRITE;
1352
1353   return AVIERR_OK;
1354 }