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