If using the default values, also set dwType to REG_SZ as our default
[wine] / dlls / avifil32 / api.c
1 /*
2  * Copyright 1999 Marcus Meissner
3  * Copyright 2002-2003 Michael Günnewig
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #define COM_NO_WINDOWS_H
21 #include <assert.h>
22 #include <stdarg.h>
23
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winnls.h"
27 #include "wingdi.h"
28 #include "winuser.h"
29 #include "winreg.h"
30 #include "winerror.h"
31 #include "windowsx.h"
32
33 #include "ole2.h"
34 #include "shellapi.h"
35 #include "vfw.h"
36 #include "msacm.h"
37
38 #include "avifile_private.h"
39
40 #include "wine/debug.h"
41 #include "wine/unicode.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(avifile);
44
45 /***********************************************************************
46  * copied from dlls/shell32/undocshell.h
47  */
48 HRESULT WINAPI SHCoCreateInstance(LPCSTR lpszClsid,REFCLSID rClsid,
49                                   LPUNKNOWN pUnkOuter,REFIID riid,LPVOID *ppv);
50
51 /***********************************************************************
52  * for AVIBuildFilterW -- uses fixed size table
53  */
54 #define MAX_FILTERS 30 /* 30 => 7kB */
55
56 typedef struct _AVIFilter {
57   WCHAR szClsid[40];
58   WCHAR szExtensions[MAX_FILTERS * 7];
59 } AVIFilter;
60
61 /***********************************************************************
62  * for AVISaveOptions
63  */
64 static struct {
65   UINT                  uFlags;
66   INT                   nStreams;
67   PAVISTREAM           *ppavis;
68   LPAVICOMPRESSOPTIONS *ppOptions;
69   INT                   nCurrent;
70 } SaveOpts;
71
72 /***********************************************************************
73  * copied from dlls/ole32/compobj.c
74  */
75 static HRESULT AVIFILE_CLSIDFromString(LPCSTR idstr, LPCLSID id)
76 {
77   BYTE const *s = (BYTE const*)idstr;
78   BYTE *p;
79   INT   i;
80   BYTE table[256];
81
82   if (!s) {
83     memset(id, 0, sizeof(CLSID));
84     return S_OK;
85   } else {  /* validate the CLSID string */
86     if (lstrlenA(s) != 38)
87       return CO_E_CLASSSTRING;
88
89     if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') ||
90         (s[24]!='-') || (s[37]!='}'))
91       return CO_E_CLASSSTRING;
92
93     for (i = 1; i < 37; i++) {
94       if ((i == 9) || (i == 14) || (i == 19) || (i == 24))
95         continue;
96       if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
97             ((s[i] >= 'a') && (s[i] <= 'f'))  ||
98             ((s[i] >= 'A') && (s[i] <= 'F')))
99           )
100         return CO_E_CLASSSTRING;
101     }
102   }
103
104   TRACE("%s -> %p\n", s, id);
105
106   /* quick lookup table */
107   memset(table, 0, 256);
108
109   for (i = 0; i < 10; i++)
110     table['0' + i] = i;
111
112   for (i = 0; i < 6; i++) {
113     table['A' + i] = i+10;
114     table['a' + i] = i+10;
115   }
116
117   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
118   p = (BYTE *) id;
119
120   s++;  /* skip leading brace  */
121   for (i = 0; i < 4; i++) {
122     p[3 - i] = table[*s]<<4 | table[*(s+1)];
123     s += 2;
124   }
125   p += 4;
126   s++;  /* skip - */
127
128   for (i = 0; i < 2; i++) {
129     p[1-i] = table[*s]<<4 | table[*(s+1)];
130     s += 2;
131   }
132   p += 2;
133   s++;  /* skip - */
134
135   for (i = 0; i < 2; i++) {
136     p[1-i] = table[*s]<<4 | table[*(s+1)];
137     s += 2;
138   }
139   p += 2;
140   s++;  /* skip - */
141
142   /* these are just sequential bytes */
143   for (i = 0; i < 2; i++) {
144     *p++ = table[*s]<<4 | table[*(s+1)];
145     s += 2;
146   }
147   s++;  /* skip - */
148
149   for (i = 0; i < 6; i++) {
150     *p++ = table[*s]<<4 | table[*(s+1)];
151     s += 2;
152   }
153
154   return S_OK;
155 }
156
157 static BOOL AVIFILE_GetFileHandlerByExtension(LPCWSTR szFile, LPCLSID lpclsid)
158 {
159   CHAR   szRegKey[25];
160   CHAR   szValue[100];
161   LPWSTR szExt = strrchrW(szFile, '.');
162   LONG   len = sizeof(szValue) / sizeof(szValue[0]);
163
164   if (szExt == NULL)
165     return FALSE;
166
167   szExt++;
168
169   wsprintfA(szRegKey, "AVIFile\\Extensions\\%.3ls", szExt);
170   if (RegQueryValueA(HKEY_CLASSES_ROOT, szRegKey, szValue, &len) != ERROR_SUCCESS)
171     return FALSE;
172
173   return (AVIFILE_CLSIDFromString(szValue, lpclsid) == S_OK);
174 }
175
176 /***********************************************************************
177  *              AVIFileInit             (AVIFIL32.@)
178  *              AVIFileInit             (AVIFILE.100)
179  */
180 void WINAPI AVIFileInit(void) {
181   /* need to load ole32.dll if not already done and get some functions */
182   FIXME("(): stub!\n");
183 }
184
185 /***********************************************************************
186  *              AVIFileExit             (AVIFIL32.@)
187  *              AVIFileExit             (AVIFILE.101)
188  */
189 void WINAPI AVIFileExit(void) {
190   /* need to free ole32.dll if we are the last exit call */
191   FIXME("(): stub!\n");
192 }
193
194 /***********************************************************************
195  *              AVIFileOpenA            (AVIFIL32.@)
196  *              AVIFileOpen             (AVIFILE.102)
197  */
198 HRESULT WINAPI AVIFileOpenA(PAVIFILE *ppfile, LPCSTR szFile, UINT uMode,
199                             LPCLSID lpHandler)
200 {
201   LPWSTR  wszFile = NULL;
202   HRESULT hr;
203   int     len;
204
205   TRACE("(%p,%s,0x%08X,%s)\n", ppfile, debugstr_a(szFile), uMode,
206         debugstr_guid(lpHandler));
207
208   /* check parameters */
209   if (ppfile == NULL || szFile == NULL)
210     return AVIERR_BADPARAM;
211
212   /* convert ASCII string to Unicode and call unicode function */
213   len = lstrlenA(szFile);
214   if (len <= 0)
215     return AVIERR_BADPARAM;
216
217   wszFile = (LPWSTR)LocalAlloc(LPTR, (len + 1) * sizeof(WCHAR));
218   if (wszFile == NULL)
219     return AVIERR_MEMORY;
220
221   MultiByteToWideChar(CP_ACP, 0, szFile, -1, wszFile, len + 1);
222   wszFile[len + 1] = 0;
223
224   hr = AVIFileOpenW(ppfile, wszFile, uMode, lpHandler);
225
226   LocalFree((HLOCAL)wszFile);
227
228   return hr;
229 }
230
231 /***********************************************************************
232  *              AVIFileOpenW            (AVIFIL32.@)
233  */
234 HRESULT WINAPI AVIFileOpenW(PAVIFILE *ppfile, LPCWSTR szFile, UINT uMode,
235                             LPCLSID lpHandler)
236 {
237   IPersistFile *ppersist = NULL;
238   CLSID         clsidHandler;
239   HRESULT       hr;
240
241   TRACE("(%p,%s,0x%X,%s)\n", ppfile, debugstr_w(szFile), uMode,
242         debugstr_guid(lpHandler));
243
244   /* check parameters */
245   if (ppfile == NULL || szFile == NULL)
246     return AVIERR_BADPARAM;
247
248   *ppfile = NULL;
249
250   /* if no handler then try guessing it by extension */
251   if (lpHandler == NULL) {
252     if (! AVIFILE_GetFileHandlerByExtension(szFile, &clsidHandler))
253       return AVIERR_UNSUPPORTED;
254   } else
255     memcpy(&clsidHandler, lpHandler, sizeof(clsidHandler));
256
257   /* crete instance of handler */
258   hr = SHCoCreateInstance(NULL, &clsidHandler, NULL,
259                           &IID_IAVIFile, (LPVOID*)ppfile);
260   if (FAILED(hr) || *ppfile == NULL)
261     return hr;
262
263   /* ask for IPersistFile interface for loading/creating the file */
264   hr = IAVIFile_QueryInterface(*ppfile, &IID_IPersistFile, (LPVOID*)&ppersist);
265   if (FAILED(hr) || ppersist == NULL) {
266     IAVIFile_Release(*ppfile);
267     *ppfile = NULL;
268     return hr;
269   }
270
271   hr = IPersistFile_Load(ppersist, szFile, uMode);
272   IPersistFile_Release(ppersist);
273   if (FAILED(hr)) {
274     IAVIFile_Release(*ppfile);
275     *ppfile = NULL;
276   }
277
278   return hr;
279 }
280
281 /***********************************************************************
282  *              AVIFileAddRef           (AVIFIL32.@)
283  *              AVIFileAddRef           (AVIFILE.140)
284  */
285 ULONG WINAPI AVIFileAddRef(PAVIFILE pfile)
286 {
287   TRACE("(%p)\n", pfile);
288
289   if (pfile == NULL) {
290     ERR(": bad handle passed!\n");
291     return 0;
292   }
293
294   return IAVIFile_AddRef(pfile);
295 }
296
297 /***********************************************************************
298  *              AVIFileRelease          (AVIFIL32.@)
299  *              AVIFileRelease          (AVIFILE.141)
300  */
301 ULONG WINAPI AVIFileRelease(PAVIFILE pfile)
302 {
303   TRACE("(%p)\n", pfile);
304
305   if (pfile == NULL) {
306     ERR(": bad handle passed!\n");
307     return 0;
308   }
309
310   return IAVIFile_Release(pfile);
311 }
312
313 /***********************************************************************
314  *              AVIFileInfo             (AVIFIL32.@)
315  *              AVIFileInfoA            (AVIFIL32.@)
316  *              AVIFileInfo             (AVIFILE.142)
317  */
318 HRESULT WINAPI AVIFileInfoA(PAVIFILE pfile, LPAVIFILEINFOA afi, LONG size)
319 {
320   AVIFILEINFOW afiw;
321   HRESULT      hres;
322
323   TRACE("(%p,%p,%ld)\n", pfile, afi, size);
324
325   if (pfile == NULL)
326     return AVIERR_BADHANDLE;
327   if ((DWORD)size < sizeof(AVIFILEINFOA))
328     return AVIERR_BADSIZE;
329
330   hres = IAVIFile_Info(pfile, &afiw, sizeof(afiw));
331
332   memcpy(afi, &afiw, sizeof(*afi) - sizeof(afi->szFileType));
333   WideCharToMultiByte(CP_ACP, 0, afiw.szFileType, -1, afi->szFileType,
334                       sizeof(afi->szFileType), NULL, NULL);
335   afi->szFileType[sizeof(afi->szFileType) - 1] = 0;
336
337   return hres;
338 }
339
340 /***********************************************************************
341  *              AVIFileInfoW            (AVIFIL32.@)
342  */
343 HRESULT WINAPI AVIFileInfoW(PAVIFILE pfile, LPAVIFILEINFOW afiw, LONG size)
344 {
345   TRACE("(%p,%p,%ld)\n", pfile, afiw, size);
346
347   if (pfile == NULL)
348     return AVIERR_BADHANDLE;
349
350   return IAVIFile_Info(pfile, afiw, size);
351 }
352
353 /***********************************************************************
354  *              AVIFileGetStream        (AVIFIL32.@)
355  *              AVIFileGetStream        (AVIFILE.143)
356  */
357 HRESULT WINAPI AVIFileGetStream(PAVIFILE pfile, PAVISTREAM *avis,
358                                 DWORD fccType, LONG lParam)
359 {
360   TRACE("(%p,%p,'%4.4s',%ld)\n", pfile, avis, (char*)&fccType, lParam);
361
362   if (pfile == NULL)
363     return AVIERR_BADHANDLE;
364
365   return IAVIFile_GetStream(pfile, avis, fccType, lParam);
366 }
367
368 /***********************************************************************
369  *              AVIFileCreateStreamA    (AVIFIL32.@)
370  *              AVIFileCreateStream     (AVIFILE.144)
371  */
372 HRESULT WINAPI AVIFileCreateStreamA(PAVIFILE pfile, PAVISTREAM *ppavi,
373                                     LPAVISTREAMINFOA psi)
374 {
375   AVISTREAMINFOW        psiw;
376
377   TRACE("(%p,%p,%p)\n", pfile, ppavi, psi);
378
379   if (pfile == NULL)
380     return AVIERR_BADHANDLE;
381
382   /* Only the szName at the end is different */
383   memcpy(&psiw, psi, sizeof(*psi) - sizeof(psi->szName));
384   MultiByteToWideChar(CP_ACP, 0, psi->szName, -1, psiw.szName,
385                       sizeof(psiw.szName) / sizeof(psiw.szName[0]));
386
387   return IAVIFile_CreateStream(pfile, ppavi, &psiw);
388 }
389
390 /***********************************************************************
391  *              AVIFileCreateStreamW    (AVIFIL32.@)
392  */
393 HRESULT WINAPI AVIFileCreateStreamW(PAVIFILE pfile, PAVISTREAM *avis,
394                                     LPAVISTREAMINFOW asi)
395 {
396   TRACE("(%p,%p,%p)\n", pfile, avis, asi);
397
398   if (pfile == NULL)
399     return AVIERR_BADHANDLE;
400
401   return IAVIFile_CreateStream(pfile, avis, asi);
402 }
403
404 /***********************************************************************
405  *              AVIFileWriteData        (AVIFIL32.@)
406  *              AVIFileWriteData        (AVIFILE.146)
407  */
408 HRESULT WINAPI AVIFileWriteData(PAVIFILE pfile,DWORD fcc,LPVOID lp,LONG size)
409 {
410   TRACE("(%p,'%4.4s',%p,%ld)\n", pfile, (char*)&fcc, lp, size);
411
412   if (pfile == NULL)
413     return AVIERR_BADHANDLE;
414
415   return IAVIFile_WriteData(pfile, fcc, lp, size);
416 }
417
418 /***********************************************************************
419  *              AVIFileReadData         (AVIFIL32.@)
420  *              AVIFileReadData         (AVIFILE.147)
421  */
422 HRESULT WINAPI AVIFileReadData(PAVIFILE pfile,DWORD fcc,LPVOID lp,LPLONG size)
423 {
424   TRACE("(%p,'%4.4s',%p,%p)\n", pfile, (char*)&fcc, lp, size);
425
426   if (pfile == NULL)
427     return AVIERR_BADHANDLE;
428
429   return IAVIFile_ReadData(pfile, fcc, lp, size);
430 }
431
432 /***********************************************************************
433  *              AVIFileEndRecord        (AVIFIL32.@)
434  *              AVIFileEndRecord        (AVIFILE.148)
435  */
436 HRESULT WINAPI AVIFileEndRecord(PAVIFILE pfile)
437 {
438   TRACE("(%p)\n", pfile);
439
440   if (pfile == NULL)
441     return AVIERR_BADHANDLE;
442
443   return IAVIFile_EndRecord(pfile);
444 }
445
446 /***********************************************************************
447  *              AVIStreamAddRef         (AVIFIL32.@)
448  *              AVIStreamAddRef         (AVIFILE.160)
449  */
450 ULONG WINAPI AVIStreamAddRef(PAVISTREAM pstream)
451 {
452   TRACE("(%p)\n", pstream);
453
454   if (pstream == NULL) {
455     ERR(": bad handle passed!\n");
456     return 0;
457   }
458
459   return IAVIStream_AddRef(pstream);
460 }
461
462 /***********************************************************************
463  *              AVIStreamRelease        (AVIFIL32.@)
464  *              AVIStreamRelease        (AVIFILE.161)
465  */
466 ULONG WINAPI AVIStreamRelease(PAVISTREAM pstream)
467 {
468   TRACE("(%p)\n", pstream);
469
470   if (pstream == NULL) {
471     ERR(": bad handle passed!\n");
472     return 0;
473   }
474
475   return IAVIStream_Release(pstream);
476 }
477
478 /***********************************************************************
479  *              AVIStreamCreate         (AVIFIL32.@)
480  *              AVIStreamCreate         (AVIFILE.104)
481  */
482 HRESULT WINAPI AVIStreamCreate(PAVISTREAM *ppavi, LONG lParam1, LONG lParam2,
483                                LPCLSID pclsidHandler)
484 {
485   HRESULT hr;
486
487   TRACE("(%p,0x%08lX,0x%08lX,%s)\n", ppavi, lParam1, lParam2,
488         debugstr_guid(pclsidHandler));
489
490   if (ppavi == NULL)
491     return AVIERR_BADPARAM;
492
493   *ppavi = NULL;
494   if (pclsidHandler == NULL)
495     return AVIERR_UNSUPPORTED;
496
497   hr = SHCoCreateInstance(NULL, pclsidHandler, NULL,
498                           &IID_IAVIStream, (LPVOID*)ppavi);
499   if (FAILED(hr) || *ppavi == NULL)
500     return hr;
501
502   hr = IAVIStream_Create(*ppavi, lParam1, lParam2);
503   if (FAILED(hr)) {
504     IAVIStream_Release(*ppavi);
505     *ppavi = NULL;
506   }
507
508   return hr;
509 }
510
511 /***********************************************************************
512  *              AVIStreamInfo           (AVIFIL32.@)
513  *              AVIStreamInfoA          (AVIFIL32.@)
514  *              AVIStreamInfo           (AVIFILE.162)
515  */
516 HRESULT WINAPI AVIStreamInfoA(PAVISTREAM pstream, LPAVISTREAMINFOA asi,
517                               LONG size)
518 {
519   AVISTREAMINFOW asiw;
520   HRESULT        hres;
521
522   TRACE("(%p,%p,%ld)\n", pstream, asi, size);
523
524   if (pstream == NULL)
525     return AVIERR_BADHANDLE;
526   if ((DWORD)size < sizeof(AVISTREAMINFOA))
527     return AVIERR_BADSIZE;
528
529   hres = IAVIStream_Info(pstream, &asiw, sizeof(asiw));
530
531   memcpy(asi, &asiw, sizeof(asiw) - sizeof(asiw.szName));
532   WideCharToMultiByte(CP_ACP, 0, asiw.szName, -1, asi->szName,
533                       sizeof(asi->szName), NULL, NULL);
534   asi->szName[sizeof(asi->szName) - 1] = 0;
535
536   return hres;
537 }
538
539 /***********************************************************************
540  *              AVIStreamInfoW          (AVIFIL32.@)
541  */
542 HRESULT WINAPI AVIStreamInfoW(PAVISTREAM pstream, LPAVISTREAMINFOW asi,
543                               LONG size)
544 {
545   TRACE("(%p,%p,%ld)\n", pstream, asi, size);
546
547   if (pstream == NULL)
548     return AVIERR_BADHANDLE;
549
550   return IAVIStream_Info(pstream, asi, size);
551 }
552
553 /***********************************************************************
554  *              AVIStreamFindSample     (AVIFIL32.@)
555  *              AVIStreamFindSample     (AVIFILE.163)
556  */
557 HRESULT WINAPI AVIStreamFindSample(PAVISTREAM pstream, LONG pos, DWORD flags)
558 {
559   TRACE("(%p,%ld,0x%lX)\n", pstream, pos, flags);
560
561   if (pstream == NULL)
562     return -1;
563
564   return IAVIStream_FindSample(pstream, pos, flags);
565 }
566
567 /***********************************************************************
568  *              AVIStreamReadFormat     (AVIFIL32.@)
569  *              AVIStreamReadFormat     (AVIFILE.164)
570  */
571 HRESULT WINAPI AVIStreamReadFormat(PAVISTREAM pstream, LONG pos,
572                                    LPVOID format, LPLONG formatsize)
573 {
574   TRACE("(%p,%ld,%p,%p)\n", pstream, pos, format, formatsize);
575
576   if (pstream == NULL)
577     return AVIERR_BADHANDLE;
578
579   return IAVIStream_ReadFormat(pstream, pos, format, formatsize);
580 }
581
582 /***********************************************************************
583  *              AVIStreamSetFormat      (AVIFIL32.@)
584  *              AVIStreamSetFormat      (AVIFILE.169)
585  */
586 HRESULT WINAPI AVIStreamSetFormat(PAVISTREAM pstream, LONG pos,
587                                   LPVOID format, LONG formatsize)
588 {
589   TRACE("(%p,%ld,%p,%ld)\n", pstream, pos, format, formatsize);
590
591   if (pstream == NULL)
592     return AVIERR_BADHANDLE;
593
594   return IAVIStream_SetFormat(pstream, pos, format, formatsize);
595 }
596
597 /***********************************************************************
598  *              AVIStreamRead           (AVIFIL32.@)
599  *              AVIStreamRead           (AVIFILE.167)
600  */
601 HRESULT WINAPI AVIStreamRead(PAVISTREAM pstream, LONG start, LONG samples,
602                              LPVOID buffer, LONG buffersize,
603                              LPLONG bytesread, LPLONG samplesread)
604 {
605   TRACE("(%p,%ld,%ld,%p,%ld,%p,%p)\n", pstream, start, samples, buffer,
606         buffersize, bytesread, samplesread);
607
608   if (pstream == NULL)
609     return AVIERR_BADHANDLE;
610
611   return IAVIStream_Read(pstream, start, samples, buffer, buffersize,
612                          bytesread, samplesread);
613 }
614
615 /***********************************************************************
616  *              AVIStreamWrite          (AVIFIL32.@)
617  *              AVIStreamWrite          (AVIFILE.168)
618  */
619 HRESULT WINAPI AVIStreamWrite(PAVISTREAM pstream, LONG start, LONG samples,
620                               LPVOID buffer, LONG buffersize, DWORD flags,
621                               LPLONG sampwritten, LPLONG byteswritten)
622 {
623   TRACE("(%p,%ld,%ld,%p,%ld,0x%lX,%p,%p)\n", pstream, start, samples, buffer,
624         buffersize, flags, sampwritten, byteswritten);
625
626   if (pstream == NULL)
627     return AVIERR_BADHANDLE;
628
629   return IAVIStream_Write(pstream, start, samples, buffer, buffersize,
630                           flags, sampwritten, byteswritten);
631 }
632
633 /***********************************************************************
634  *              AVIStreamReadData       (AVIFIL32.@)
635  *              AVIStreamReadData       (AVIFILE.165)
636  */
637 HRESULT WINAPI AVIStreamReadData(PAVISTREAM pstream, DWORD fcc, LPVOID lp,
638                                  LPLONG lpread)
639 {
640   TRACE("(%p,'%4.4s',%p,%p)\n", pstream, (char*)&fcc, lp, lpread);
641
642   if (pstream == NULL)
643     return AVIERR_BADHANDLE;
644
645   return IAVIStream_ReadData(pstream, fcc, lp, lpread);
646 }
647
648 /***********************************************************************
649  *              AVIStreamWriteData      (AVIFIL32.@)
650  *              AVIStreamWriteData      (AVIFILE.166)
651  */
652 HRESULT WINAPI AVIStreamWriteData(PAVISTREAM pstream, DWORD fcc, LPVOID lp,
653                                   LONG size)
654 {
655   TRACE("(%p,'%4.4s',%p,%ld)\n", pstream, (char*)&fcc, lp, size);
656
657   if (pstream == NULL)
658     return AVIERR_BADHANDLE;
659
660   return IAVIStream_WriteData(pstream, fcc, lp, size);
661 }
662
663 /***********************************************************************
664  *              AVIStreamGetFrameOpen   (AVIFIL32.@)
665  *              AVIStreamGetFrameOpen   (AVIFILE.112)
666  */
667 PGETFRAME WINAPI AVIStreamGetFrameOpen(PAVISTREAM pstream,
668                                        LPBITMAPINFOHEADER lpbiWanted)
669 {
670   PGETFRAME pg = NULL;
671
672   TRACE("(%p,%p)\n", pstream, lpbiWanted);
673
674   if (FAILED(IAVIStream_QueryInterface(pstream, &IID_IGetFrame, (LPVOID*)&pg)) ||
675       pg == NULL) {
676     pg = AVIFILE_CreateGetFrame(pstream);
677     if (pg == NULL)
678       return NULL;
679   }
680
681   if (FAILED(IGetFrame_SetFormat(pg, lpbiWanted, NULL, 0, 0, -1, -1))) {
682     IGetFrame_Release(pg);
683     return NULL;
684   }
685
686   return pg;
687 }
688
689 /***********************************************************************
690  *              AVIStreamGetFrame       (AVIFIL32.@)
691  *              AVIStreamGetFrame       (AVIFILE.110)
692  */
693 LPVOID WINAPI AVIStreamGetFrame(PGETFRAME pg, LONG pos)
694 {
695   TRACE("(%p,%ld)\n", pg, pos);
696
697   if (pg == NULL)
698     return NULL;
699
700   return IGetFrame_GetFrame(pg, pos);
701 }
702
703 /***********************************************************************
704  *              AVIStreamGetFrameClose  (AVIFIL32.@)
705  *              AVIStreamGetFrameClose  (AVIFILE.111)
706  */
707 HRESULT WINAPI AVIStreamGetFrameClose(PGETFRAME pg)
708 {
709   TRACE("(%p)\n", pg);
710
711   if (pg != NULL)
712     return IGetFrame_Release(pg);
713   return 0;
714 }
715
716 /***********************************************************************
717  *              AVIMakeCompressedStream (AVIFIL32.@)
718  */
719 HRESULT WINAPI AVIMakeCompressedStream(PAVISTREAM *ppsCompressed,
720                                        PAVISTREAM psSource,
721                                        LPAVICOMPRESSOPTIONS aco,
722                                        LPCLSID pclsidHandler)
723 {
724   AVISTREAMINFOW asiw;
725   CHAR           szRegKey[25];
726   CHAR           szValue[100];
727   CLSID          clsidHandler;
728   HRESULT        hr;
729   LONG           size = sizeof(szValue);
730
731   TRACE("(%p,%p,%p,%s)\n", ppsCompressed, psSource, aco,
732         debugstr_guid(pclsidHandler));
733
734   if (ppsCompressed == NULL)
735     return AVIERR_BADPARAM;
736   if (psSource == NULL)
737     return AVIERR_BADHANDLE;
738
739   *ppsCompressed = NULL;
740
741   /* if no handler given get default ones based on streamtype */
742   if (pclsidHandler == NULL) {
743     hr = IAVIStream_Info(psSource, &asiw, sizeof(asiw));
744     if (FAILED(hr))
745       return hr;
746
747     wsprintfA(szRegKey, "AVIFile\\Compressors\\%4.4s", (char*)&asiw.fccType);
748     if (RegQueryValueA(HKEY_CLASSES_ROOT, szRegKey, szValue, &size) != ERROR_SUCCESS)
749       return AVIERR_UNSUPPORTED;
750     if (AVIFILE_CLSIDFromString(szValue, &clsidHandler) != S_OK)
751       return AVIERR_UNSUPPORTED;
752   } else
753     memcpy(&clsidHandler, pclsidHandler, sizeof(clsidHandler));
754
755   hr = SHCoCreateInstance(NULL, &clsidHandler, NULL,
756                           &IID_IAVIStream, (LPVOID*)ppsCompressed);
757   if (FAILED(hr) || *ppsCompressed == NULL)
758     return hr;
759
760   hr = IAVIStream_Create(*ppsCompressed, (LPARAM)psSource, (LPARAM)aco);
761   if (FAILED(hr)) {
762     IAVIStream_Release(*ppsCompressed);
763     *ppsCompressed = NULL;
764   }
765
766   return hr;
767 }
768
769 /***********************************************************************
770  *              AVIMakeFileFromStreams  (AVIFIL32.@)
771  */
772 HRESULT WINAPI AVIMakeFileFromStreams(PAVIFILE *ppfile, int nStreams,
773                                       PAVISTREAM *ppStreams)
774 {
775   TRACE("(%p,%d,%p)\n", ppfile, nStreams, ppStreams);
776
777   if (nStreams < 0 || ppfile == NULL || ppStreams == NULL)
778     return AVIERR_BADPARAM;
779
780   *ppfile = AVIFILE_CreateAVITempFile(nStreams, ppStreams);
781   if (*ppfile == NULL)
782     return AVIERR_MEMORY;
783
784   return AVIERR_OK;
785 }
786
787 /***********************************************************************
788  *              AVIStreamOpenFromFile   (AVIFILE.103)
789  *              AVIStreamOpenFromFileA  (AVIFIL32.@)
790  */
791 HRESULT WINAPI AVIStreamOpenFromFileA(PAVISTREAM *ppavi, LPCSTR szFile,
792                                       DWORD fccType, LONG lParam,
793                                       UINT mode, LPCLSID pclsidHandler)
794 {
795   PAVIFILE pfile = NULL;
796   HRESULT  hr;
797
798   TRACE("(%p,%s,'%4.4s',%ld,0x%X,%s)\n", ppavi, debugstr_a(szFile),
799         (char*)&fccType, lParam, mode, debugstr_guid(pclsidHandler));
800
801   if (ppavi == NULL || szFile == NULL)
802     return AVIERR_BADPARAM;
803
804   *ppavi = NULL;
805
806   hr = AVIFileOpenA(&pfile, szFile, mode, pclsidHandler);
807   if (FAILED(hr) || pfile == NULL)
808     return hr;
809
810   hr = IAVIFile_GetStream(pfile, ppavi, fccType, lParam);
811   IAVIFile_Release(pfile);
812
813   return hr;
814 }
815
816 /***********************************************************************
817  *              AVIStreamOpenFromFileW  (AVIFIL32.@)
818  */
819 HRESULT WINAPI AVIStreamOpenFromFileW(PAVISTREAM *ppavi, LPCWSTR szFile,
820                                       DWORD fccType, LONG lParam,
821                                       UINT mode, LPCLSID pclsidHandler)
822 {
823   PAVIFILE pfile = NULL;
824   HRESULT  hr;
825
826   TRACE("(%p,%s,'%4.4s',%ld,0x%X,%s)\n", ppavi, debugstr_w(szFile),
827         (char*)&fccType, lParam, mode, debugstr_guid(pclsidHandler));
828
829   if (ppavi == NULL || szFile == NULL)
830     return AVIERR_BADPARAM;
831
832   *ppavi = NULL;
833
834   hr = AVIFileOpenW(&pfile, szFile, mode, pclsidHandler);
835   if (FAILED(hr) || pfile == NULL)
836     return hr;
837
838   hr = IAVIFile_GetStream(pfile, ppavi, fccType, lParam);
839   IAVIFile_Release(pfile);
840
841   return hr;
842 }
843
844 /***********************************************************************
845  *              AVIStreamBeginStreaming (AVIFIL32.@)
846  */
847 LONG WINAPI AVIStreamBeginStreaming(PAVISTREAM pavi, LONG lStart, LONG lEnd, LONG lRate)
848 {
849   IAVIStreaming* pstream = NULL;
850   HRESULT hr;
851
852   TRACE("(%p,%ld,%ld,%ld)\n", pavi, lStart, lEnd, lRate);
853
854   if (pavi == NULL)
855     return AVIERR_BADHANDLE;
856
857   hr = IAVIStream_QueryInterface(pavi, &IID_IAVIStreaming, (LPVOID*)&pstream);
858   if (SUCCEEDED(hr) && pstream != NULL) {
859     hr = IAVIStreaming_Begin(pstream, lStart, lEnd, lRate);
860     IAVIStreaming_Release(pstream);
861   } else
862     hr = AVIERR_OK;
863
864   return hr;
865 }
866
867 /***********************************************************************
868  *              AVIStreamEndStreaming   (AVIFIL32.@)
869  */
870 LONG WINAPI AVIStreamEndStreaming(PAVISTREAM pavi)
871 {
872   IAVIStreaming* pstream = NULL;
873   HRESULT hr;
874
875   TRACE("(%p)\n", pavi);
876
877   hr = IAVIStream_QueryInterface(pavi, &IID_IAVIStreaming, (LPVOID*)&pstream);
878   if (SUCCEEDED(hr) && pstream != NULL) {
879     IAVIStreaming_End(pstream);
880     IAVIStreaming_Release(pstream);
881   }
882
883  return AVIERR_OK;
884 }
885
886 /***********************************************************************
887  *              AVIStreamStart          (AVIFILE.130)
888  *              AVIStreamStart          (AVIFIL32.@)
889  */
890 LONG WINAPI AVIStreamStart(PAVISTREAM pstream)
891 {
892   AVISTREAMINFOW asiw;
893
894   TRACE("(%p)\n", pstream);
895
896   if (pstream == NULL)
897     return 0;
898
899   if (FAILED(IAVIStream_Info(pstream, &asiw, sizeof(asiw))))
900     return 0;
901
902   return asiw.dwStart;
903 }
904
905 /***********************************************************************
906  *              AVIStreamLength         (AVIFILE.131)
907  *              AVIStreamLength         (AVIFIL32.@)
908  */
909 LONG WINAPI AVIStreamLength(PAVISTREAM pstream)
910 {
911   AVISTREAMINFOW asiw;
912
913   TRACE("(%p)\n", pstream);
914
915   if (pstream == NULL)
916     return 0;
917
918   if (FAILED(IAVIStream_Info(pstream, &asiw, sizeof(asiw))))
919     return 0;
920
921   return asiw.dwLength;
922 }
923
924 /***********************************************************************
925  *              AVIStreamSampleToTime   (AVIFILE.133)
926  *              AVIStreamSampleToTime   (AVIFIL32.@)
927  */
928 LONG WINAPI AVIStreamSampleToTime(PAVISTREAM pstream, LONG lSample)
929 {
930   AVISTREAMINFOW asiw;
931   LONG time;
932
933   TRACE("(%p,%ld)\n", pstream, lSample);
934
935   if (pstream == NULL)
936     return -1;
937
938   if (FAILED(IAVIStream_Info(pstream, &asiw, sizeof(asiw))))
939     return -1;
940   if (asiw.dwRate == 0)
941     return -1;
942
943   /* limit to stream bounds */
944   if (lSample < asiw.dwStart)
945     lSample = asiw.dwStart;
946   if (lSample > asiw.dwStart + asiw.dwLength)
947     lSample = asiw.dwStart + asiw.dwLength;
948
949   if (asiw.dwRate / asiw.dwScale < 1000)
950     time = (LONG)(((float)lSample * asiw.dwScale * 1000) / asiw.dwRate);
951   else
952     time = (LONG)(((float)lSample * asiw.dwScale * 1000 + (asiw.dwRate - 1)) / asiw.dwRate);
953
954   TRACE(" -> %ld\n",time);
955   return time;
956 }
957
958 /***********************************************************************
959  *              AVIStreamTimeToSample   (AVIFILE.132)
960  *              AVIStreamTimeToSample   (AVIFIL32.@)
961  */
962 LONG WINAPI AVIStreamTimeToSample(PAVISTREAM pstream, LONG lTime)
963 {
964   AVISTREAMINFOW asiw;
965   LONG sample;
966
967   TRACE("(%p,%ld)\n", pstream, lTime);
968
969   if (pstream == NULL || lTime < 0)
970     return -1;
971
972   if (FAILED(IAVIStream_Info(pstream, &asiw, sizeof(asiw))))
973     return -1;
974   if (asiw.dwScale == 0)
975     return -1;
976
977   if (asiw.dwRate / asiw.dwScale < 1000)
978     sample = (LONG)((((float)asiw.dwRate * lTime) / (asiw.dwScale * 1000)));
979   else
980     sample = (LONG)(((float)asiw.dwRate * lTime + (asiw.dwScale * 1000 - 1)) / (asiw.dwScale * 1000));
981
982   /* limit to stream bounds */
983   if (sample < asiw.dwStart)
984     sample = asiw.dwStart;
985   if (sample > asiw.dwStart + asiw.dwLength)
986     sample = asiw.dwStart + asiw.dwLength;
987
988   TRACE(" -> %ld\n", sample);
989   return sample;
990 }
991
992 /***********************************************************************
993  *              AVIBuildFilterA         (AVIFIL32.@)
994  *              AVIBuildFilter          (AVIFILE.123)
995  */
996 HRESULT WINAPI AVIBuildFilterA(LPSTR szFilter, LONG cbFilter, BOOL fSaving)
997 {
998   LPWSTR  wszFilter;
999   HRESULT hr;
1000
1001   TRACE("(%p,%ld,%d)\n", szFilter, cbFilter, fSaving);
1002
1003   /* check parameters */
1004   if (szFilter == NULL)
1005     return AVIERR_BADPARAM;
1006   if (cbFilter < 2)
1007     return AVIERR_BADSIZE;
1008
1009   szFilter[0] = 0;
1010   szFilter[1] = 0;
1011
1012   wszFilter = (LPWSTR)GlobalAllocPtr(GHND, cbFilter * sizeof(WCHAR));
1013   if (wszFilter == NULL)
1014     return AVIERR_MEMORY;
1015
1016   hr = AVIBuildFilterW(wszFilter, cbFilter, fSaving);
1017   if (SUCCEEDED(hr)) {
1018     WideCharToMultiByte(CP_ACP, 0, wszFilter, cbFilter,
1019                         szFilter, cbFilter, NULL, NULL);
1020   }
1021
1022   GlobalFreePtr(wszFilter);
1023
1024   return hr;
1025 }
1026
1027 /***********************************************************************
1028  *              AVIBuildFilterW         (AVIFIL32.@)
1029  */
1030 HRESULT WINAPI AVIBuildFilterW(LPWSTR szFilter, LONG cbFilter, BOOL fSaving)
1031 {
1032   static const WCHAR szClsid[] = {'C','L','S','I','D',0};
1033   static const WCHAR szExtensionFmt[] = {';','*','.','%','s',0};
1034   static const WCHAR szAVIFileExtensions[] =
1035     {'A','V','I','F','i','l','e','\\','E','x','t','e','n','s','i','o','n','s',0};
1036
1037   AVIFilter *lp;
1038   WCHAR      szAllFiles[40];
1039   WCHAR      szFileExt[10];
1040   WCHAR      szValue[128];
1041   HKEY       hKey;
1042   DWORD      n, i;
1043   LONG       size;
1044   DWORD      count = 0;
1045
1046   TRACE("(%p,%ld,%d)\n", szFilter, cbFilter, fSaving);
1047
1048   /* check parameters */
1049   if (szFilter == NULL)
1050     return AVIERR_BADPARAM;
1051   if (cbFilter < 2)
1052     return AVIERR_BADSIZE;
1053
1054   lp = (AVIFilter*)GlobalAllocPtr(GHND, MAX_FILTERS * sizeof(AVIFilter));
1055   if (lp == NULL)
1056     return AVIERR_MEMORY;
1057
1058   /*
1059    * 1. iterate over HKEY_CLASSES_ROOT\\AVIFile\\Extensions and collect
1060    *    extensions and CLSID's
1061    * 2. iterate over collected CLSID's and copy it's description and it's
1062    *    extensions to szFilter if it fits
1063    *
1064    * First filter is named "All multimedia files" and it's filter is a
1065    * collection of all possible extensions except "*.*".
1066    */
1067   if (RegOpenKeyW(HKEY_CLASSES_ROOT, szAVIFileExtensions, &hKey) != S_OK) {
1068     GlobalFreePtr(lp);
1069     return AVIERR_ERROR;
1070   }
1071   for (n = 0;RegEnumKeyW(hKey, n, szFileExt, sizeof(szFileExt)) == S_OK;n++) {
1072     /* get CLSID to extension */
1073     size = sizeof(szValue)/sizeof(szValue[0]);
1074     if (RegQueryValueW(hKey, szFileExt, szValue, &size) != S_OK)
1075       break;
1076
1077     /* search if the CLSID is already known */
1078     for (i = 1; i <= count; i++) {
1079       if (lstrcmpW(lp[i].szClsid, szValue) == 0)
1080         break; /* a new one */
1081     }
1082
1083     if (count - i == -1U) {
1084       /* it's a new CLSID */
1085
1086       /* FIXME: How do we get info's about read/write capabilities? */
1087
1088       if (count >= MAX_FILTERS) {
1089         /* try to inform user of our full fixed size table */
1090         ERR(": More than %d filters found! Adjust MAX_FILTERS in dlls/avifil32/api.c\n", MAX_FILTERS);
1091         break;
1092       }
1093
1094       lstrcpyW(lp[i].szClsid, szValue);
1095
1096       count++;
1097     }
1098
1099     /* append extension to the filter */
1100     wsprintfW(szValue, szExtensionFmt, szFileExt);
1101     if (lp[i].szExtensions[0] == 0)
1102       lstrcatW(lp[i].szExtensions, szValue + 1);
1103     else
1104       lstrcatW(lp[i].szExtensions, szValue);
1105
1106     /* also append to the "all multimedia"-filter */
1107     if (lp[0].szExtensions[0] == 0)
1108       lstrcatW(lp[0].szExtensions, szValue + 1);
1109     else
1110       lstrcatW(lp[0].szExtensions, szValue);
1111   }
1112   RegCloseKey(hKey);
1113
1114   /* 2. get descriptions for the CLSIDs and fill out szFilter */
1115   if (RegOpenKeyW(HKEY_CLASSES_ROOT, szClsid, &hKey) != S_OK) {
1116     GlobalFreePtr(lp);
1117     return AVIERR_ERROR;
1118   }
1119   for (n = 0; n <= count; n++) {
1120     /* first the description */
1121     if (n != 0) {
1122       size = sizeof(szValue)/sizeof(szValue[0]);
1123       if (RegQueryValueW(hKey, lp[n].szClsid, szValue, &size) == S_OK) {
1124         size = lstrlenW(szValue);
1125         lstrcpynW(szFilter, szValue, cbFilter);
1126       }
1127     } else
1128       size = LoadStringW(AVIFILE_hModule,IDS_ALLMULTIMEDIA,szFilter,cbFilter);
1129
1130     /* check for enough space */
1131     size++;
1132     if (cbFilter < size + lstrlenW(lp[n].szExtensions) + 2) {
1133       szFilter[0] = 0;
1134       szFilter[1] = 0;
1135       GlobalFreePtr(lp);
1136       RegCloseKey(hKey);
1137       return AVIERR_BUFFERTOOSMALL;
1138     }
1139     cbFilter -= size;
1140     szFilter += size;
1141
1142     /* and then the filter */
1143     lstrcpynW(szFilter, lp[n].szExtensions, cbFilter);
1144     size = lstrlenW(lp[n].szExtensions) + 1;
1145     cbFilter -= size;
1146     szFilter += size;
1147   }
1148
1149   RegCloseKey(hKey);
1150   GlobalFreePtr(lp);
1151
1152   /* add "All files" "*.*" filter if enough space left */
1153   size = LoadStringW(AVIFILE_hModule, IDS_ALLFILES,
1154                      szAllFiles, sizeof(szAllFiles)) + 1;
1155   if (cbFilter > size) {
1156     int i;
1157
1158     /* replace '@' with \000 to separate description of filter */
1159     for (i = 0; i < size && szAllFiles[i] != 0; i++) {
1160       if (szAllFiles[i] == '@') {
1161         szAllFiles[i] = 0;
1162         break;
1163       }
1164     }
1165       
1166     memcpy(szFilter, szAllFiles, size * sizeof(szAllFiles[0]));
1167     szFilter += size;
1168     szFilter[0] = 0;
1169
1170     return AVIERR_OK;
1171   } else {
1172     szFilter[0] = 0;
1173     return AVIERR_BUFFERTOOSMALL;
1174   }
1175 }
1176
1177 static BOOL AVISaveOptionsFmtChoose(HWND hWnd)
1178 {
1179   LPAVICOMPRESSOPTIONS pOptions = SaveOpts.ppOptions[SaveOpts.nCurrent];
1180   AVISTREAMINFOW       sInfo;
1181
1182   TRACE("(%p)\n", hWnd);
1183
1184   if (pOptions == NULL || SaveOpts.ppavis[SaveOpts.nCurrent] == NULL) {
1185     ERR(": bad state!\n");
1186     return FALSE;
1187   }
1188
1189   if (FAILED(AVIStreamInfoW(SaveOpts.ppavis[SaveOpts.nCurrent],
1190                             &sInfo, sizeof(sInfo)))) {
1191     ERR(": AVIStreamInfoW failed!\n");
1192     return FALSE;
1193   }
1194
1195   if (sInfo.fccType == streamtypeVIDEO) {
1196     COMPVARS cv;
1197     BOOL     ret;
1198
1199     memset(&cv, 0, sizeof(cv));
1200
1201     if ((pOptions->dwFlags & AVICOMPRESSF_VALID) == 0) {
1202       memset(pOptions, 0, sizeof(AVICOMPRESSOPTIONS));
1203       pOptions->fccType    = streamtypeVIDEO;
1204       pOptions->fccHandler = comptypeDIB;
1205       pOptions->dwQuality  = (DWORD)ICQUALITY_DEFAULT;
1206     }
1207
1208     cv.cbSize     = sizeof(cv);
1209     cv.dwFlags    = ICMF_COMPVARS_VALID;
1210     /*cv.fccType    = pOptions->fccType; */
1211     cv.fccHandler = pOptions->fccHandler;
1212     cv.lQ         = pOptions->dwQuality;
1213     cv.lpState    = pOptions->lpParms;
1214     cv.cbState    = pOptions->cbParms;
1215     if (pOptions->dwFlags & AVICOMPRESSF_KEYFRAMES)
1216       cv.lKey = pOptions->dwKeyFrameEvery;
1217     else
1218       cv.lKey = 0;
1219     if (pOptions->dwFlags & AVICOMPRESSF_DATARATE)
1220       cv.lDataRate = pOptions->dwBytesPerSecond / 1024; /* need kBytes */
1221     else
1222       cv.lDataRate = 0;
1223
1224     ret = ICCompressorChoose(hWnd, SaveOpts.uFlags, NULL,
1225                              SaveOpts.ppavis[SaveOpts.nCurrent], &cv, NULL);
1226
1227     if (ret) {
1228       pOptions->fccHandler = cv.fccHandler;
1229       pOptions->lpParms   = cv.lpState;
1230       pOptions->cbParms   = cv.cbState;
1231       pOptions->dwQuality = cv.lQ;
1232       if (cv.lKey != 0) {
1233         pOptions->dwKeyFrameEvery = cv.lKey;
1234         pOptions->dwFlags |= AVICOMPRESSF_KEYFRAMES;
1235       } else
1236         pOptions->dwFlags &= ~AVICOMPRESSF_KEYFRAMES;
1237       if (cv.lDataRate != 0) {
1238         pOptions->dwBytesPerSecond = cv.lDataRate * 1024; /* need bytes */
1239         pOptions->dwFlags |= AVICOMPRESSF_DATARATE;
1240       } else
1241         pOptions->dwFlags &= ~AVICOMPRESSF_DATARATE;
1242       pOptions->dwFlags  |= AVICOMPRESSF_VALID;
1243     }
1244     ICCompressorFree(&cv);
1245
1246     return ret;
1247   } else if (sInfo.fccType == streamtypeAUDIO) {
1248     ACMFORMATCHOOSEW afmtc;
1249     MMRESULT         ret;
1250     LONG             size;
1251
1252     /* FIXME: check ACM version -- Which version is needed? */
1253
1254     memset(&afmtc, 0, sizeof(afmtc));
1255     afmtc.cbStruct  = sizeof(afmtc);
1256     afmtc.fdwStyle  = 0;
1257     afmtc.hwndOwner = hWnd;
1258
1259     acmMetrics(NULL, ACM_METRIC_MAX_SIZE_FORMAT, &size);
1260     if ((pOptions->cbFormat == 0 || pOptions->lpFormat == NULL) && size != 0) {
1261       pOptions->lpFormat = GlobalAllocPtr(GMEM_MOVEABLE, size);
1262       pOptions->cbFormat = size;
1263     } else if (pOptions->cbFormat < (DWORD)size) {
1264       pOptions->lpFormat = GlobalReAllocPtr(pOptions->lpFormat, size, GMEM_MOVEABLE);
1265       pOptions->cbFormat = size;
1266     }
1267     if (pOptions->lpFormat == NULL)
1268       return FALSE;
1269     afmtc.pwfx  = pOptions->lpFormat;
1270     afmtc.cbwfx = pOptions->cbFormat;
1271
1272     size = 0;
1273     AVIStreamFormatSize(SaveOpts.ppavis[SaveOpts.nCurrent],
1274                         sInfo.dwStart, &size);
1275     if (size < (LONG)sizeof(PCMWAVEFORMAT))
1276       size = sizeof(PCMWAVEFORMAT);
1277     afmtc.pwfxEnum = GlobalAllocPtr(GHND, size);
1278     if (afmtc.pwfxEnum != NULL) {
1279       AVIStreamReadFormat(SaveOpts.ppavis[SaveOpts.nCurrent],
1280                           sInfo.dwStart, afmtc.pwfxEnum, &size);
1281       afmtc.fdwEnum = ACM_FORMATENUMF_CONVERT;
1282     }
1283
1284     ret = acmFormatChooseW(&afmtc);
1285     if (ret == S_OK)
1286       pOptions->dwFlags |= AVICOMPRESSF_VALID;
1287
1288     if (afmtc.pwfxEnum != NULL)
1289       GlobalFreePtr(afmtc.pwfxEnum);
1290
1291     return (ret == S_OK ? TRUE : FALSE);
1292   } else {
1293     ERR(": unknown streamtype 0x%08lX\n", sInfo.fccType);
1294     return FALSE;
1295   }
1296 }
1297
1298 static void AVISaveOptionsUpdate(HWND hWnd)
1299 {
1300   static const WCHAR szVideoFmt[]={'%','l','d','x','%','l','d','x','%','d',0};
1301   static const WCHAR szAudioFmt[]={'%','s',' ','%','s',0};
1302
1303   WCHAR          szFormat[128];
1304   AVISTREAMINFOW sInfo;
1305   LPVOID         lpFormat;
1306   LONG           size;
1307
1308   TRACE("(%p)\n", hWnd);
1309
1310   SaveOpts.nCurrent = SendDlgItemMessageW(hWnd,IDC_STREAM,CB_GETCURSEL,0,0);
1311   if (SaveOpts.nCurrent < 0)
1312     return;
1313
1314   if (FAILED(AVIStreamInfoW(SaveOpts.ppavis[SaveOpts.nCurrent], &sInfo, sizeof(sInfo))))
1315     return;
1316
1317   AVIStreamFormatSize(SaveOpts.ppavis[SaveOpts.nCurrent],sInfo.dwStart,&size);
1318   if (size > 0) {
1319     szFormat[0] = 0;
1320
1321     /* read format to build format descriotion string */
1322     lpFormat = GlobalAllocPtr(GHND, size);
1323     if (lpFormat != NULL) {
1324       if (SUCCEEDED(AVIStreamReadFormat(SaveOpts.ppavis[SaveOpts.nCurrent],sInfo.dwStart,lpFormat, &size))) {
1325         if (sInfo.fccType == streamtypeVIDEO) {
1326           LPBITMAPINFOHEADER lpbi = lpFormat;
1327           ICINFO icinfo;
1328
1329           wsprintfW(szFormat, szVideoFmt, lpbi->biWidth,
1330                     lpbi->biHeight, lpbi->biBitCount);
1331
1332           if (lpbi->biCompression != BI_RGB) {
1333             HIC    hic;
1334
1335             hic = ICLocate(ICTYPE_VIDEO, sInfo.fccHandler, lpFormat,
1336                            NULL, ICMODE_DECOMPRESS);
1337             if (hic != NULL) {
1338               if (ICGetInfo(hic, &icinfo, sizeof(icinfo)) == S_OK)
1339                 lstrcatW(szFormat, icinfo.szDescription);
1340               ICClose(hic);
1341             }
1342           } else {
1343             LoadStringW(AVIFILE_hModule, IDS_UNCOMPRESSED,
1344                         icinfo.szDescription, sizeof(icinfo.szDescription));
1345             lstrcatW(szFormat, icinfo.szDescription);
1346           }
1347         } else if (sInfo.fccType == streamtypeAUDIO) {
1348           ACMFORMATTAGDETAILSW aftd;
1349           ACMFORMATDETAILSW    afd;
1350
1351           memset(&aftd, 0, sizeof(aftd));
1352           memset(&afd, 0, sizeof(afd));
1353
1354           aftd.cbStruct     = sizeof(aftd);
1355           aftd.dwFormatTag  = afd.dwFormatTag =
1356             ((PWAVEFORMATEX)lpFormat)->wFormatTag;
1357           aftd.cbFormatSize = afd.cbwfx = size;
1358
1359           afd.cbStruct      = sizeof(afd);
1360           afd.pwfx          = lpFormat;
1361
1362           if (acmFormatTagDetailsW(NULL, &aftd,
1363                                    ACM_FORMATTAGDETAILSF_FORMATTAG) == S_OK) {
1364             if (acmFormatDetailsW(NULL,&afd,ACM_FORMATDETAILSF_FORMAT) == S_OK)
1365               wsprintfW(szFormat, szAudioFmt, afd.szFormat, aftd.szFormatTag);
1366           }
1367         }
1368       }
1369       GlobalFreePtr(lpFormat);
1370     }
1371
1372     /* set text for format description */
1373     SetDlgItemTextW(hWnd, IDC_FORMATTEXT, szFormat);
1374
1375     /* Disable option button for unsupported streamtypes */
1376     if (sInfo.fccType == streamtypeVIDEO ||
1377         sInfo.fccType == streamtypeAUDIO)
1378       EnableWindow(GetDlgItem(hWnd, IDC_OPTIONS), TRUE);
1379     else
1380       EnableWindow(GetDlgItem(hWnd, IDC_OPTIONS), FALSE);
1381   }
1382
1383 }
1384
1385 INT_PTR CALLBACK AVISaveOptionsDlgProc(HWND hWnd, UINT uMsg,
1386                                     WPARAM wParam, LPARAM lParam)
1387 {
1388   DWORD dwInterleave;
1389   BOOL  bIsInterleaved;
1390   INT   n;
1391
1392   /*TRACE("(%p,%u,0x%04X,0x%08lX)\n", hWnd, uMsg, wParam, lParam);*/
1393
1394   switch (uMsg) {
1395   case WM_INITDIALOG:
1396     SaveOpts.nCurrent = 0;
1397     if (SaveOpts.nStreams == 1) {
1398       EndDialog(hWnd, AVISaveOptionsFmtChoose(hWnd));
1399       return TRUE;
1400     }
1401
1402     /* add streams */
1403     for (n = 0; n < SaveOpts.nStreams; n++) {
1404       AVISTREAMINFOW sInfo;
1405
1406       AVIStreamInfoW(SaveOpts.ppavis[n], &sInfo, sizeof(sInfo));
1407       SendDlgItemMessageW(hWnd, IDC_STREAM, CB_ADDSTRING,
1408                           0L, (LPARAM)sInfo.szName);
1409     }
1410
1411     /* select first stream */
1412     SendDlgItemMessageW(hWnd, IDC_STREAM, CB_SETCURSEL, 0, 0);
1413     SendMessageW(hWnd, WM_COMMAND,
1414                  GET_WM_COMMAND_MPS(IDC_STREAM, hWnd, CBN_SELCHANGE));
1415
1416     /* initialize interleave */
1417     if (SaveOpts.ppOptions[0] != NULL &&
1418         (SaveOpts.ppOptions[0]->dwFlags & AVICOMPRESSF_VALID)) {
1419       bIsInterleaved = (SaveOpts.ppOptions[0]->dwFlags & AVICOMPRESSF_INTERLEAVE);
1420       dwInterleave = SaveOpts.ppOptions[0]->dwInterleaveEvery;
1421     } else {
1422       bIsInterleaved = TRUE;
1423       dwInterleave   = 0;
1424     }
1425     CheckDlgButton(hWnd, IDC_INTERLEAVE, bIsInterleaved);
1426     SetDlgItemInt(hWnd, IDC_INTERLEAVEEVERY, dwInterleave, FALSE);
1427     EnableWindow(GetDlgItem(hWnd, IDC_INTERLEAVEEVERY), bIsInterleaved);
1428     break;
1429   case WM_COMMAND:
1430     switch (GET_WM_COMMAND_ID(wParam, lParam)) {
1431     case IDOK:
1432       /* get data from controls and save them */
1433       dwInterleave   = GetDlgItemInt(hWnd, IDC_INTERLEAVEEVERY, NULL, 0);
1434       bIsInterleaved = IsDlgButtonChecked(hWnd, IDC_INTERLEAVE);
1435       for (n = 0; n < SaveOpts.nStreams; n++) {
1436         if (SaveOpts.ppOptions[n] != NULL) {
1437           if (bIsInterleaved) {
1438             SaveOpts.ppOptions[n]->dwFlags |= AVICOMPRESSF_INTERLEAVE;
1439             SaveOpts.ppOptions[n]->dwInterleaveEvery = dwInterleave;
1440           } else
1441             SaveOpts.ppOptions[n]->dwFlags &= ~AVICOMPRESSF_INTERLEAVE;
1442         }
1443       }
1444       /* fall through */
1445     case IDCANCEL:
1446       EndDialog(hWnd, GET_WM_COMMAND_ID(wParam, lParam) == IDOK);
1447       break;
1448     case IDC_INTERLEAVE:
1449       EnableWindow(GetDlgItem(hWnd, IDC_INTERLEAVEEVERY),
1450                    IsDlgButtonChecked(hWnd, IDC_INTERLEAVE));
1451       break;
1452     case IDC_STREAM:
1453       if (GET_WM_COMMAND_CMD(wParam, lParam) == CBN_SELCHANGE) {
1454         /* update control elements */
1455         AVISaveOptionsUpdate(hWnd);
1456       }
1457       break;
1458     case IDC_OPTIONS:
1459       AVISaveOptionsFmtChoose(hWnd);
1460       break;
1461     };
1462     return TRUE;
1463   };
1464
1465   return FALSE;
1466 }
1467
1468 /***********************************************************************
1469  *              AVISaveOptions          (AVIFIL32.@)
1470  */
1471 BOOL WINAPI AVISaveOptions(HWND hWnd, UINT uFlags, INT nStreams,
1472                            PAVISTREAM *ppavi, LPAVICOMPRESSOPTIONS *ppOptions)
1473 {
1474   LPAVICOMPRESSOPTIONS pSavedOptions = NULL;
1475   INT ret, n;
1476
1477   TRACE("(%p,0x%X,%d,%p,%p)\n", hWnd, uFlags, nStreams,
1478         ppavi, ppOptions);
1479
1480   /* check parameters */
1481   if (nStreams <= 0 || ppavi == NULL || ppOptions == NULL)
1482     return AVIERR_BADPARAM;
1483
1484   /* save options for case user press cancel */
1485   if (ppOptions != NULL && nStreams > 1) {
1486     pSavedOptions = GlobalAllocPtr(GHND,nStreams * sizeof(AVICOMPRESSOPTIONS));
1487     if (pSavedOptions == NULL)
1488       return FALSE;
1489
1490     for (n = 0; n < nStreams; n++) {
1491       if (ppOptions[n] != NULL)
1492         memcpy(pSavedOptions + n, ppOptions[n], sizeof(AVICOMPRESSOPTIONS));
1493     }
1494   }
1495
1496   SaveOpts.uFlags    = uFlags;
1497   SaveOpts.nStreams  = nStreams;
1498   SaveOpts.ppavis    = ppavi;
1499   SaveOpts.ppOptions = ppOptions;
1500
1501   ret = DialogBoxW(AVIFILE_hModule, MAKEINTRESOURCEW(IDD_SAVEOPTIONS),
1502                    hWnd, AVISaveOptionsDlgProc);
1503
1504   if (ret == -1)
1505     ret = FALSE;
1506
1507   /* restore options when user pressed cancel */
1508   if (pSavedOptions != NULL) {
1509     if (ret == FALSE) {
1510       for (n = 0; n < nStreams; n++) {
1511         if (ppOptions[n] != NULL)
1512           memcpy(ppOptions[n], pSavedOptions + n, sizeof(AVICOMPRESSOPTIONS));
1513       }
1514     }
1515     GlobalFreePtr(pSavedOptions);
1516   }
1517
1518   return (BOOL)ret;
1519 }
1520
1521 /***********************************************************************
1522  *              AVISaveOptionsFree      (AVIFIL32.@)
1523  *              AVISaveOptionsFree      (AVIFILE.124)
1524  */
1525 HRESULT WINAPI AVISaveOptionsFree(INT nStreams,LPAVICOMPRESSOPTIONS*ppOptions)
1526 {
1527   TRACE("(%d,%p)\n", nStreams, ppOptions);
1528
1529   if (nStreams < 0 || ppOptions == NULL)
1530     return AVIERR_BADPARAM;
1531
1532   for (; nStreams > 0; nStreams--) {
1533     if (ppOptions[nStreams] != NULL) {
1534       ppOptions[nStreams]->dwFlags &= ~AVICOMPRESSF_VALID;
1535
1536       if (ppOptions[nStreams]->lpParms != NULL) {
1537         GlobalFreePtr(ppOptions[nStreams]->lpParms);
1538         ppOptions[nStreams]->lpParms = NULL;
1539         ppOptions[nStreams]->cbParms = 0;
1540       }
1541       if (ppOptions[nStreams]->lpFormat != NULL) {
1542         GlobalFreePtr(ppOptions[nStreams]->lpFormat);
1543         ppOptions[nStreams]->lpFormat = NULL;
1544         ppOptions[nStreams]->cbFormat = 0;
1545       }
1546     }
1547   }
1548
1549   return AVIERR_OK;
1550 }
1551
1552 /***********************************************************************
1553  *              AVISaveVA               (AVIFIL32.@)
1554  */
1555 HRESULT WINAPI AVISaveVA(LPCSTR szFile, CLSID *pclsidHandler,
1556                          AVISAVECALLBACK lpfnCallback, int nStream,
1557                          PAVISTREAM *ppavi, LPAVICOMPRESSOPTIONS *plpOptions)
1558 {
1559   LPWSTR  wszFile = NULL;
1560   HRESULT hr;
1561   int     len;
1562
1563   TRACE("%s,%p,%p,%d,%p,%p)\n", debugstr_a(szFile), pclsidHandler,
1564         lpfnCallback, nStream, ppavi, plpOptions);
1565
1566   if (szFile == NULL || ppavi == NULL || plpOptions == NULL)
1567     return AVIERR_BADPARAM;
1568
1569   /* convert ASCII string to Unicode and call Unicode function */
1570   len = lstrlenA(szFile);
1571   if (len <= 0)
1572     return AVIERR_BADPARAM;
1573
1574   wszFile = (LPWSTR)LocalAlloc(LPTR, (len + 1) * sizeof(WCHAR));
1575   if (wszFile == NULL)
1576     return AVIERR_MEMORY;
1577
1578   MultiByteToWideChar(CP_ACP, 0, szFile, -1, wszFile, len + 1);
1579   wszFile[len + 1] = 0;
1580
1581   hr = AVISaveVW(wszFile, pclsidHandler, lpfnCallback,
1582                  nStream, ppavi, plpOptions);
1583
1584   LocalFree((HLOCAL)wszFile);
1585
1586   return hr;
1587 }
1588
1589 /***********************************************************************
1590  *              AVIFILE_AVISaveDefaultCallback  (internal)
1591  */
1592 static BOOL WINAPI AVIFILE_AVISaveDefaultCallback(INT progress)
1593 {
1594   TRACE("(%d)\n", progress);
1595
1596   return FALSE;
1597 }
1598
1599 /***********************************************************************
1600  *              AVISaveVW               (AVIFIL32.@)
1601  */
1602 HRESULT WINAPI AVISaveVW(LPCWSTR szFile, CLSID *pclsidHandler,
1603                          AVISAVECALLBACK lpfnCallback, int nStreams,
1604                          PAVISTREAM *ppavi, LPAVICOMPRESSOPTIONS *plpOptions)
1605 {
1606   LONG           lStart[MAX_AVISTREAMS];
1607   PAVISTREAM     pOutStreams[MAX_AVISTREAMS];
1608   PAVISTREAM     pInStreams[MAX_AVISTREAMS];
1609   AVIFILEINFOW   fInfo;
1610   AVISTREAMINFOW sInfo;
1611
1612   PAVIFILE       pfile = NULL; /* the output AVI file */
1613   LONG           lFirstVideo = -1;
1614   int            curStream;
1615
1616   /* for interleaving ... */
1617   DWORD          dwInterleave = 0; /* interleave rate */
1618   DWORD          dwFileInitialFrames;
1619   LONG           lFileLength;
1620   LONG           lSampleInc;
1621
1622   /* for reading/writing the data ... */
1623   LPVOID         lpBuffer = NULL;
1624   LONG           cbBuffer;        /* real size of lpBuffer */
1625   LONG           lBufferSize;     /* needed bytes for format(s), etc. */
1626   LONG           lReadBytes;
1627   LONG           lReadSamples;
1628   HRESULT        hres;
1629
1630   TRACE("(%s,%p,%p,%d,%p,%p)\n", debugstr_w(szFile), pclsidHandler,
1631         lpfnCallback, nStreams, ppavi, plpOptions);
1632
1633   if (szFile == NULL || ppavi == NULL || plpOptions == NULL)
1634     return AVIERR_BADPARAM;
1635   if (nStreams >= MAX_AVISTREAMS) {
1636     WARN("Can't write AVI with %d streams only supports %d -- change MAX_AVISTREAMS!\n", nStreams, MAX_AVISTREAMS);
1637     return AVIERR_INTERNAL;
1638   }
1639
1640   if (lpfnCallback == NULL)
1641     lpfnCallback = AVIFILE_AVISaveDefaultCallback;
1642
1643   /* clear local variable(s) */
1644   for (curStream = 0; curStream < nStreams; curStream++) {
1645     pInStreams[curStream]  = NULL;
1646     pOutStreams[curStream] = NULL;
1647   }
1648
1649   /* open output AVI file (create it if it doesn't exist) */
1650   hres = AVIFileOpenW(&pfile, szFile, OF_CREATE|OF_SHARE_EXCLUSIVE|OF_WRITE,
1651                       pclsidHandler);
1652   if (FAILED(hres))
1653     return hres;
1654   AVIFileInfoW(pfile, &fInfo, sizeof(fInfo)); /* for dwCaps */
1655
1656   /* initialize our data structures part 1 */
1657   for (curStream = 0; curStream < nStreams; curStream++) {
1658     PAVISTREAM pCurStream = ppavi[curStream];
1659
1660     hres = AVIStreamInfoW(pCurStream, &sInfo, sizeof(sInfo));
1661     if (FAILED(hres))
1662       goto error;
1663
1664     /* search first video stream and check for interleaving */
1665     if (sInfo.fccType == streamtypeVIDEO) {
1666       /* remember first video stream -- needed for interleaving */
1667       if (lFirstVideo < 0)
1668         lFirstVideo = curStream;
1669     } else if (!dwInterleave && plpOptions != NULL) {
1670       /* check if any non-video stream wants to be interleaved */
1671       WARN("options.flags=0x%lX options.dwInterleave=%lu\n",plpOptions[curStream]->dwFlags,plpOptions[curStream]->dwInterleaveEvery);
1672       if (plpOptions[curStream] != NULL &&
1673           plpOptions[curStream]->dwFlags & AVICOMPRESSF_INTERLEAVE)
1674         dwInterleave = plpOptions[curStream]->dwInterleaveEvery;
1675     }
1676
1677     /* create de-/compressed stream interface if needed */
1678     pInStreams[curStream] = NULL;
1679     if (plpOptions != NULL && plpOptions[curStream] != NULL) {
1680       if (plpOptions[curStream]->fccHandler ||
1681           plpOptions[curStream]->lpFormat != NULL) {
1682         DWORD dwKeySave = plpOptions[curStream]->dwKeyFrameEvery;
1683
1684         if (fInfo.dwCaps & AVIFILECAPS_ALLKEYFRAMES)
1685           plpOptions[curStream]->dwKeyFrameEvery = 1;
1686
1687         hres = AVIMakeCompressedStream(&pInStreams[curStream], pCurStream,
1688                                        plpOptions[curStream], NULL);
1689         plpOptions[curStream]->dwKeyFrameEvery = dwKeySave;
1690         if (FAILED(hres) || pInStreams[curStream] == NULL) {
1691           pInStreams[curStream] = NULL;
1692           goto error;
1693         }
1694
1695         /* test stream interface and update stream-info */
1696         hres = AVIStreamInfoW(pInStreams[curStream], &sInfo, sizeof(sInfo));
1697         if (FAILED(hres))
1698           goto error;
1699       }
1700     }
1701
1702     /* now handle streams which will only be copied */
1703     if (pInStreams[curStream] == NULL) {
1704       pCurStream = pInStreams[curStream] = ppavi[curStream];
1705       AVIStreamAddRef(pCurStream);
1706     } else
1707       pCurStream = pInStreams[curStream];
1708
1709     lStart[curStream] = sInfo.dwStart;
1710   } /* for all streams */
1711
1712   /* check that first video stream is the first stream */
1713   if (lFirstVideo > 0) {
1714     PAVISTREAM pTmp = pInStreams[lFirstVideo];
1715     LONG lTmp = lStart[lFirstVideo];
1716
1717     pInStreams[lFirstVideo] = pInStreams[0];
1718     pInStreams[0] = pTmp;
1719     lStart[lFirstVideo] = lStart[0];
1720     lStart[0] = lTmp;
1721     lFirstVideo = 0;
1722   }
1723
1724   /* allocate buffer for formats, data, etc. of an initiale size of 64 kByte */
1725   lpBuffer = GlobalAllocPtr(GPTR, cbBuffer = 0x00010000);
1726   if (lpBuffer == NULL) {
1727     hres = AVIERR_MEMORY;
1728     goto error;
1729   }
1730
1731   AVIStreamInfoW(pInStreams[0], &sInfo, sizeof(sInfo));
1732   lFileLength = sInfo.dwLength;
1733   dwFileInitialFrames = 0;
1734   if (lFirstVideo >= 0) {
1735     /* check for correct version of the format
1736      *  -- need atleast BITMAPINFOHEADER or newer
1737      */
1738     lSampleInc = 1;
1739     lBufferSize = cbBuffer;
1740     hres = AVIStreamReadFormat(pInStreams[lFirstVideo], AVIStreamStart(pInStreams[lFirstVideo]), lpBuffer, &lBufferSize);
1741     if (lBufferSize < (LONG)sizeof(BITMAPINFOHEADER))
1742       hres = AVIERR_INTERNAL;
1743     if (FAILED(hres))
1744       goto error;
1745   } else /* use one second blocks for interleaving if no video present */
1746     lSampleInc = AVIStreamTimeToSample(pInStreams[0], 1000000);
1747
1748   /* create output streams */
1749   for (curStream = 0; curStream < nStreams; curStream++) {
1750     AVIStreamInfoW(pInStreams[curStream], &sInfo, sizeof(sInfo));
1751
1752     sInfo.dwInitialFrames = 0;
1753     if (dwInterleave != 0 && curStream > 0 && sInfo.fccType != streamtypeVIDEO) {
1754       /* 750 ms initial frames for non-video streams */
1755       sInfo.dwInitialFrames = AVIStreamTimeToSample(pInStreams[0], 750);
1756     }
1757
1758     hres = AVIFileCreateStreamW(pfile, &pOutStreams[curStream], &sInfo);
1759     if (pOutStreams[curStream] != NULL && SUCCEEDED(hres)) {
1760       /* copy initial format for this stream */
1761       lBufferSize = cbBuffer;
1762       hres = AVIStreamReadFormat(pInStreams[curStream], sInfo.dwStart,
1763                                  lpBuffer, &lBufferSize);
1764       if (FAILED(hres))
1765         goto error;
1766       hres = AVIStreamSetFormat(pOutStreams[curStream], 0, lpBuffer, lBufferSize);
1767       if (FAILED(hres))
1768         goto error;
1769
1770       /* try to copy stream handler data */
1771       lBufferSize = cbBuffer;
1772       hres = AVIStreamReadData(pInStreams[curStream], ckidSTREAMHANDLERDATA,
1773                                lpBuffer, &lBufferSize);
1774       if (SUCCEEDED(hres) && lBufferSize > 0) {
1775         hres = AVIStreamWriteData(pOutStreams[curStream],ckidSTREAMHANDLERDATA,
1776                                   lpBuffer, lBufferSize);
1777         if (FAILED(hres))
1778           goto error;
1779       }
1780
1781       if (dwFileInitialFrames < sInfo.dwInitialFrames)
1782         dwFileInitialFrames = sInfo.dwInitialFrames;
1783       lReadBytes =
1784         AVIStreamSampleToSample(pOutStreams[0], pInStreams[curStream],
1785                                 sInfo.dwLength);
1786       if (lFileLength < lReadBytes)
1787         lFileLength = lReadBytes;
1788     } else {
1789       /* creation of de-/compression stream interface failed */
1790       WARN("creation of (de-)compression stream failed for stream %d\n",curStream);
1791       AVIStreamRelease(pInStreams[curStream]);
1792       if (curStream + 1 >= nStreams) {
1793         /* move the others one up */
1794         PAVISTREAM *ppas = &pInStreams[curStream];
1795         int            n = nStreams - (curStream + 1);
1796
1797         do {
1798           *ppas = pInStreams[curStream + 1];
1799         } while (--n);
1800       }
1801       nStreams--;
1802       curStream--;
1803     }
1804   } /* create output streams for all input streams */
1805
1806   /* have we still something to write, or lost everything? */
1807   if (nStreams <= 0)
1808     goto error;
1809
1810   if (dwInterleave) {
1811     LONG lCurFrame = -dwFileInitialFrames;
1812
1813     /* interleaved file */
1814     if (dwInterleave == 1)
1815       AVIFileEndRecord(pfile);
1816
1817     for (; lCurFrame < lFileLength; lCurFrame += lSampleInc) {
1818       for (curStream = 0; curStream < nStreams; curStream++) {
1819         LONG lLastSample;
1820
1821         hres = AVIStreamInfoW(pOutStreams[curStream], &sInfo, sizeof(sInfo));
1822         if (FAILED(hres))
1823           goto error;
1824
1825         /* initial frames phase at the end for this stream? */
1826         if (-(LONG)sInfo.dwInitialFrames > lCurFrame)
1827           continue;
1828
1829         if ((lFileLength - lSampleInc) <= lCurFrame) {
1830           lLastSample = AVIStreamLength(pInStreams[curStream]);
1831           lFirstVideo = lLastSample + AVIStreamStart(pInStreams[curStream]);
1832         } else {
1833           if (curStream != 0) {
1834             lFirstVideo =
1835               AVIStreamSampleToSample(pInStreams[curStream], pInStreams[0],
1836                                       (sInfo.fccType == streamtypeVIDEO ? 
1837                                        (LONG)dwInterleave : lSampleInc) +
1838                                       sInfo.dwInitialFrames + lCurFrame);
1839           } else
1840             lFirstVideo = lSampleInc + (sInfo.dwInitialFrames + lCurFrame);
1841
1842           lLastSample = AVIStreamEnd(pInStreams[curStream]);
1843           if (lLastSample <= lFirstVideo)
1844             lFirstVideo = lLastSample;
1845         }
1846
1847         /* copy needed samples now */
1848         WARN("copy from stream %d samples %ld to %ld...\n",curStream,
1849               lStart[curStream],lFirstVideo);
1850         while (lFirstVideo > lStart[curStream]) {
1851           DWORD flags = 0;
1852
1853           /* copy format for case it can change */
1854           lBufferSize = cbBuffer;
1855           hres = AVIStreamReadFormat(pInStreams[curStream], lStart[curStream],
1856                                      lpBuffer, &lBufferSize);
1857           if (FAILED(hres))
1858             goto error;
1859           AVIStreamSetFormat(pOutStreams[curStream], lStart[curStream],
1860                              lpBuffer, lBufferSize);
1861
1862           /* try to read data until we got it, or error */
1863           do {
1864             hres = AVIStreamRead(pInStreams[curStream], lStart[curStream],
1865                                  lFirstVideo - lStart[curStream], lpBuffer,
1866                                  cbBuffer, &lReadBytes, &lReadSamples);
1867           } while ((hres == AVIERR_BUFFERTOOSMALL) &&
1868                    (lpBuffer = GlobalReAllocPtr(lpBuffer, cbBuffer *= 2, GPTR)) != NULL);
1869           if (lpBuffer == NULL)
1870             hres = AVIERR_MEMORY;
1871           if (FAILED(hres))
1872             goto error;
1873
1874           if (AVIStreamIsKeyFrame(pInStreams[curStream], (LONG)sInfo.dwStart))
1875             flags = AVIIF_KEYFRAME;
1876           hres = AVIStreamWrite(pOutStreams[curStream], -1, lReadSamples,
1877                                 lpBuffer, lReadBytes, flags, NULL, NULL);
1878           if (FAILED(hres))
1879             goto error;
1880
1881           lStart[curStream] += lReadSamples;
1882         }
1883         lStart[curStream] = lFirstVideo;
1884       } /* stream by stream */
1885
1886       /* need to close this block? */
1887       if (dwInterleave == 1) {
1888         hres = AVIFileEndRecord(pfile);
1889         if (FAILED(hres))
1890           break;
1891       }
1892
1893       /* show progress */
1894       if (lpfnCallback(MulDiv(dwFileInitialFrames + lCurFrame, 100,
1895                               dwFileInitialFrames + lFileLength))) {
1896         hres = AVIERR_USERABORT;
1897         break;
1898       }
1899     } /* copy frame by frame */
1900   } else {
1901     /* non-interleaved file */
1902
1903     for (curStream = 0; curStream < nStreams; curStream++) {
1904       /* show progress */
1905       if (lpfnCallback(MulDiv(curStream, 100, nStreams))) {
1906         hres = AVIERR_USERABORT;
1907         goto error;
1908       }
1909
1910       AVIStreamInfoW(pInStreams[curStream], &sInfo, sizeof(sInfo));
1911
1912       if (sInfo.dwSampleSize != 0) {
1913         /* sample-based data like audio */
1914         while (sInfo.dwStart < sInfo.dwLength) {
1915           LONG lSamples = cbBuffer / sInfo.dwSampleSize;
1916
1917           /* copy format for case it can change */
1918           lBufferSize = cbBuffer;
1919           hres = AVIStreamReadFormat(pInStreams[curStream], sInfo.dwStart,
1920                                      lpBuffer, &lBufferSize);
1921           if (FAILED(hres))
1922             return hres;
1923           AVIStreamSetFormat(pOutStreams[curStream], sInfo.dwStart,
1924                              lpBuffer, lBufferSize);
1925
1926           /* limit to stream boundaries */
1927           if (lSamples != (LONG)(sInfo.dwLength - sInfo.dwStart))
1928             lSamples = sInfo.dwLength - sInfo.dwStart;
1929
1930           /* now try to read until we got it, or error occures */
1931           do {
1932             lReadBytes   = cbBuffer;
1933             lReadSamples = 0;
1934             hres = AVIStreamRead(pInStreams[curStream],sInfo.dwStart,lSamples,
1935                                  lpBuffer,cbBuffer,&lReadBytes,&lReadSamples);
1936           } while ((hres == AVIERR_BUFFERTOOSMALL) &&
1937                    (lpBuffer = GlobalReAllocPtr(lpBuffer, cbBuffer *= 2, GPTR)) != NULL);
1938           if (lpBuffer == NULL)
1939             hres = AVIERR_MEMORY;
1940           if (FAILED(hres))
1941             goto error;
1942           if (lReadSamples != 0) {
1943             sInfo.dwStart += lReadSamples;
1944             hres = AVIStreamWrite(pOutStreams[curStream], -1, lReadSamples,
1945                                   lpBuffer, lReadBytes, 0, NULL , NULL);
1946             if (FAILED(hres))
1947               goto error;
1948
1949             /* show progress */
1950             if (lpfnCallback(MulDiv(sInfo.dwStart,100,nStreams*sInfo.dwLength)+
1951                              MulDiv(curStream, 100, nStreams))) {
1952               hres = AVIERR_USERABORT;
1953               goto error;
1954             }
1955           } else {
1956             if ((sInfo.dwLength - sInfo.dwStart) != 1) {
1957               hres = AVIERR_FILEREAD;
1958               goto error;
1959             }
1960           }
1961         }
1962       } else {
1963         /* block-based data like video */
1964         for (; sInfo.dwStart < sInfo.dwLength; sInfo.dwStart++) {
1965           DWORD flags = 0;
1966
1967           /* copy format for case it can change */
1968           lBufferSize = cbBuffer;
1969           hres = AVIStreamReadFormat(pInStreams[curStream], sInfo.dwStart,
1970                                      lpBuffer, &lBufferSize);
1971           if (FAILED(hres))
1972             goto error;
1973           AVIStreamSetFormat(pOutStreams[curStream], sInfo.dwStart,
1974                              lpBuffer, lBufferSize);
1975
1976           /* try to read block and resize buffer if necessary */
1977           do {
1978             lReadSamples = 0;
1979             lReadBytes   = cbBuffer;
1980             hres = AVIStreamRead(pInStreams[curStream], sInfo.dwStart, 1,
1981                                  lpBuffer, cbBuffer,&lReadBytes,&lReadSamples);
1982           } while ((hres == AVIERR_BUFFERTOOSMALL) &&
1983                    (lpBuffer = GlobalReAllocPtr(lpBuffer, cbBuffer *= 2, GPTR)) != NULL);
1984           if (lpBuffer == NULL)
1985             hres = AVIERR_MEMORY;
1986           if (FAILED(hres))
1987             goto error;
1988           if (lReadSamples != 1) {
1989             hres = AVIERR_FILEREAD;
1990             goto error;
1991           }
1992
1993           if (AVIStreamIsKeyFrame(pInStreams[curStream], (LONG)sInfo.dwStart))
1994             flags = AVIIF_KEYFRAME;
1995           hres = AVIStreamWrite(pOutStreams[curStream], -1, lReadSamples,
1996                                 lpBuffer, lReadBytes, flags, NULL, NULL);
1997           if (FAILED(hres))
1998             goto error;
1999
2000           /* show progress */
2001           if (lpfnCallback(MulDiv(sInfo.dwStart,100,nStreams*sInfo.dwLength)+
2002                            MulDiv(curStream, 100, nStreams))) {
2003             hres = AVIERR_USERABORT;
2004             goto error;
2005           }
2006         } /* copy all blocks */
2007       }
2008     } /* copy data stream by stream */
2009   }
2010
2011  error:
2012   if (lpBuffer != NULL)
2013     GlobalFreePtr(lpBuffer);
2014   if (pfile != NULL) {
2015     for (curStream = 0; curStream < nStreams; curStream++) {
2016       if (pOutStreams[curStream] != NULL)
2017         AVIStreamRelease(pOutStreams[curStream]);
2018       if (pInStreams[curStream] != NULL)
2019         AVIStreamRelease(pInStreams[curStream]);
2020     }
2021
2022     AVIFileRelease(pfile);
2023   }
2024
2025   return hres;
2026 }
2027
2028 /***********************************************************************
2029  *              CreateEditableStream    (AVIFIL32.@)
2030  */
2031 HRESULT WINAPI CreateEditableStream(PAVISTREAM *ppEditable, PAVISTREAM pSource)
2032 {
2033   IAVIEditStream *pEdit = NULL;
2034   HRESULT         hr;
2035
2036   TRACE("(%p,%p)\n", ppEditable, pSource);
2037
2038   if (ppEditable == NULL)
2039     return AVIERR_BADPARAM;
2040
2041   *ppEditable = NULL;
2042
2043   if (pSource != NULL) {
2044     hr = IAVIStream_QueryInterface(pSource, &IID_IAVIEditStream,
2045                                    (LPVOID*)&pEdit);
2046     if (SUCCEEDED(hr) && pEdit != NULL) {
2047       hr = IAVIEditStream_Clone(pEdit, ppEditable);
2048       IAVIEditStream_Release(pEdit);
2049
2050       return hr;
2051     }
2052   }
2053
2054   /* need own implementation of IAVIEditStream */
2055   pEdit = AVIFILE_CreateEditStream(pSource);
2056   if (pEdit == NULL)
2057     return AVIERR_MEMORY;
2058
2059   hr = IAVIEditStream_QueryInterface(pEdit, &IID_IAVIStream,
2060                                      (LPVOID*)ppEditable);
2061   IAVIEditStream_Release(pEdit);
2062
2063   return hr;
2064 }
2065
2066 /***********************************************************************
2067  *              EditStreamClone         (AVIFIL32.@)
2068  */
2069 HRESULT WINAPI EditStreamClone(PAVISTREAM pStream, PAVISTREAM *ppResult)
2070 {
2071   PAVIEDITSTREAM pEdit = NULL;
2072   HRESULT        hr;
2073
2074   TRACE("(%p,%p)\n", pStream, ppResult);
2075
2076   if (pStream == NULL)
2077     return AVIERR_BADHANDLE;
2078   if (ppResult == NULL)
2079     return AVIERR_BADPARAM;
2080
2081   *ppResult = NULL;
2082
2083   hr = IAVIStream_QueryInterface(pStream, &IID_IAVIEditStream,(LPVOID*)&pEdit);
2084   if (SUCCEEDED(hr) && pEdit != NULL) {
2085     hr = IAVIEditStream_Clone(pEdit, ppResult);
2086
2087     IAVIEditStream_Release(pEdit);
2088   } else
2089     hr = AVIERR_UNSUPPORTED;
2090
2091   return hr;
2092 }
2093
2094 /***********************************************************************
2095  *              EditStreamCopy          (AVIFIL32.@)
2096  */
2097 HRESULT WINAPI EditStreamCopy(PAVISTREAM pStream, LONG *plStart,
2098                               LONG *plLength, PAVISTREAM *ppResult)
2099 {
2100   PAVIEDITSTREAM pEdit = NULL;
2101   HRESULT        hr;
2102
2103   TRACE("(%p,%p,%p,%p)\n", pStream, plStart, plLength, ppResult);
2104
2105   if (pStream == NULL)
2106     return AVIERR_BADHANDLE;
2107   if (plStart == NULL || plLength == NULL || ppResult == NULL)
2108     return AVIERR_BADPARAM;
2109
2110   *ppResult = NULL;
2111
2112   hr = IAVIStream_QueryInterface(pStream, &IID_IAVIEditStream,(LPVOID*)&pEdit);
2113   if (SUCCEEDED(hr) && pEdit != NULL) {
2114     hr = IAVIEditStream_Copy(pEdit, plStart, plLength, ppResult);
2115
2116     IAVIEditStream_Release(pEdit);
2117   } else
2118     hr = AVIERR_UNSUPPORTED;
2119
2120   return hr;
2121 }
2122
2123 /***********************************************************************
2124  *              EditStreamCut           (AVIFIL32.@)
2125  */
2126 HRESULT WINAPI EditStreamCut(PAVISTREAM pStream, LONG *plStart,
2127                              LONG *plLength, PAVISTREAM *ppResult)
2128 {
2129   PAVIEDITSTREAM pEdit = NULL;
2130   HRESULT        hr;
2131
2132   TRACE("(%p,%p,%p,%p)\n", pStream, plStart, plLength, ppResult);
2133
2134   if (ppResult != NULL)
2135     *ppResult = NULL;
2136   if (pStream == NULL)
2137     return AVIERR_BADHANDLE;
2138   if (plStart == NULL || plLength == NULL)
2139     return AVIERR_BADPARAM;
2140
2141   hr = IAVIStream_QueryInterface(pStream, &IID_IAVIEditStream,(LPVOID*)&pEdit);
2142   if (SUCCEEDED(hr) && pEdit != NULL) {
2143     hr = IAVIEditStream_Cut(pEdit, plStart, plLength, ppResult);
2144
2145     IAVIEditStream_Release(pEdit);
2146   } else
2147     hr = AVIERR_UNSUPPORTED;
2148
2149   return hr;
2150 }
2151
2152 /***********************************************************************
2153  *              EditStreamPaste         (AVIFIL32.@)
2154  */
2155 HRESULT WINAPI EditStreamPaste(PAVISTREAM pDest, LONG *plStart, LONG *plLength,
2156                                PAVISTREAM pSource, LONG lStart, LONG lEnd)
2157 {
2158   PAVIEDITSTREAM pEdit = NULL;
2159   HRESULT        hr;
2160
2161   TRACE("(%p,%p,%p,%p,%ld,%ld)\n", pDest, plStart, plLength,
2162         pSource, lStart, lEnd);
2163
2164   if (pDest == NULL || pSource == NULL)
2165     return AVIERR_BADHANDLE;
2166   if (plStart == NULL || plLength == NULL || lStart < 0)
2167     return AVIERR_BADPARAM;
2168
2169   hr = IAVIStream_QueryInterface(pDest, &IID_IAVIEditStream,(LPVOID*)&pEdit);
2170   if (SUCCEEDED(hr) && pEdit != NULL) {
2171     hr = IAVIEditStream_Paste(pEdit, plStart, plLength, pSource, lStart, lEnd);
2172
2173     IAVIEditStream_Release(pEdit);
2174   } else
2175     hr = AVIERR_UNSUPPORTED;
2176
2177   return hr;
2178 }
2179
2180 /***********************************************************************
2181  *              EditStreamSetInfoA      (AVIFIL32.@)
2182  */
2183 HRESULT WINAPI EditStreamSetInfoA(PAVISTREAM pstream, LPAVISTREAMINFOA asi,
2184                                   LONG size)
2185 {
2186   AVISTREAMINFOW asiw;
2187
2188   TRACE("(%p,%p,%ld)\n", pstream, asi, size);
2189
2190   if (pstream == NULL)
2191     return AVIERR_BADHANDLE;
2192   if ((DWORD)size < sizeof(AVISTREAMINFOA))
2193     return AVIERR_BADSIZE;
2194
2195   memcpy(&asiw, asi, sizeof(asiw) - sizeof(asiw.szName));
2196   MultiByteToWideChar(CP_ACP, 0, asi->szName, -1,
2197                       asiw.szName, sizeof(asiw.szName));
2198
2199   return EditStreamSetInfoW(pstream, &asiw, sizeof(asiw));
2200 }
2201
2202 /***********************************************************************
2203  *              EditStreamSetInfoW      (AVIFIL32.@)
2204  */
2205 HRESULT WINAPI EditStreamSetInfoW(PAVISTREAM pstream, LPAVISTREAMINFOW asi,
2206                                   LONG size)
2207 {
2208   PAVIEDITSTREAM pEdit = NULL;
2209   HRESULT        hr;
2210
2211   TRACE("(%p,%p,%ld)\n", pstream, asi, size);
2212
2213   hr = IAVIStream_QueryInterface(pstream, &IID_IAVIEditStream,(LPVOID*)&pEdit);
2214   if (SUCCEEDED(hr) && pEdit != NULL) {
2215     hr = IAVIEditStream_SetInfo(pEdit, asi, size);
2216
2217     IAVIEditStream_Release(pEdit);
2218   } else
2219     hr = AVIERR_UNSUPPORTED;
2220
2221   return hr;
2222 }
2223
2224 /***********************************************************************
2225  *              EditStreamSetNameA      (AVIFIL32.@)
2226  */
2227 HRESULT WINAPI EditStreamSetNameA(PAVISTREAM pstream, LPCSTR szName)
2228 {
2229   AVISTREAMINFOA asia;
2230   HRESULT        hres;
2231
2232   TRACE("(%p,%s)\n", pstream, debugstr_a(szName));
2233
2234   if (pstream == NULL)
2235     return AVIERR_BADHANDLE;
2236   if (szName == NULL)
2237     return AVIERR_BADPARAM;
2238
2239   hres = AVIStreamInfoA(pstream, &asia, sizeof(asia));
2240   if (FAILED(hres))
2241     return hres;
2242
2243   memset(asia.szName, 0, sizeof(asia.szName));
2244   lstrcpynA(asia.szName, szName, sizeof(asia.szName)/sizeof(asia.szName[0]));
2245
2246   return EditStreamSetInfoA(pstream, &asia, sizeof(asia));
2247 }
2248
2249 /***********************************************************************
2250  *              EditStreamSetNameW      (AVIFIL32.@)
2251  */
2252 HRESULT WINAPI EditStreamSetNameW(PAVISTREAM pstream, LPCWSTR szName)
2253 {
2254   AVISTREAMINFOW asiw;
2255   HRESULT        hres;
2256
2257   TRACE("(%p,%s)\n", pstream, debugstr_w(szName));
2258
2259   if (pstream == NULL)
2260     return AVIERR_BADHANDLE;
2261   if (szName == NULL)
2262     return AVIERR_BADPARAM;
2263
2264   hres = IAVIStream_Info(pstream, &asiw, sizeof(asiw));
2265   if (FAILED(hres))
2266     return hres;
2267
2268   memset(asiw.szName, 0, sizeof(asiw.szName));
2269   lstrcpynW(asiw.szName, szName, sizeof(asiw.szName)/sizeof(asiw.szName[0]));
2270
2271   return EditStreamSetInfoW(pstream, &asiw, sizeof(asiw));
2272 }
2273
2274 /***********************************************************************
2275  *              AVIClearClipboard       (AVIFIL32.@)
2276  */
2277 HRESULT WINAPI AVIClearClipboard(void)
2278 {
2279   TRACE("()\n");
2280
2281   return AVIERR_UNSUPPORTED; /* OleSetClipboard(NULL); */
2282 }
2283
2284 /***********************************************************************
2285  *              AVIGetFromClipboard     (AVIFIL32.@)
2286  */
2287 HRESULT WINAPI AVIGetFromClipboard(PAVIFILE *ppfile)
2288 {
2289   FIXME("(%p), stub!\n", ppfile);
2290
2291   *ppfile = NULL;
2292
2293   return AVIERR_UNSUPPORTED;
2294 }
2295
2296 /***********************************************************************
2297  *              AVIPutFileOnClipboard   (AVIFIL32.@)
2298  */
2299 HRESULT WINAPI AVIPutFileOnClipboard(PAVIFILE pfile)
2300 {
2301   FIXME("(%p), stub!\n", pfile);
2302
2303   if (pfile == NULL)
2304     return AVIERR_BADHANDLE;
2305
2306   return AVIERR_UNSUPPORTED;
2307 }