r1006: configure: Use libx264_pic instead of libx264 if available.
[cinelerra_cv/mob.git] / cinelerra / fileogg.C
blob804ea70b42b112b4cd5f9be51383a515ba74ab42
1 #include "asset.h"
2 #include "bcsignals.h"
3 #include "byteorder.h"
4 #include "clip.h"
5 #include "edit.h"
6 #include "file.h"
7 #include "fileogg.h"
8 #include "guicast.h"
9 #include "language.h"
10 #include "mutex.h"
11 #include "mwindow.inc"
12 #include "quicktime.h"
13 #include "vframe.h"
14 #include "videodevice.inc"
15 #include "cmodel_permutation.h"
16 #include "interlacemodes.h"
17 #include "mainerror.h"
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <errno.h>
26 // Needed for packaging engine
27 #include "preferences.h"
28 #include "render.h"
30 #define READ_SIZE 66000
32 /* This code was aspired by ffmpeg2theora */
33 /* Special thanks for help on this code goes out to j@v2v.cc */
36 FileOGG::FileOGG(Asset *asset, File *file)
37  : FileBase(asset, file)
39         if(asset->format == FILE_UNKNOWN)
40                 asset->format = FILE_OGG;
41         asset->byte_order = 0;
42         reset_parameters();
43         final_write = 1;
46 FileOGG::~FileOGG()
48         if (tf) 
49         {
51                 if (tf->videosync) 
52                 {
53                         ogg_sync_clear(&tf->videosync->sync);
54                         delete tf->videosync;
55                         theora_info_clear(&tf->ti);
56                         theora_comment_clear(&tf->tc);
57                 }
58                 if (tf->audiosync) 
59                 {
60                         ogg_sync_clear(&tf->audiosync->sync);
61                         delete tf->audiosync;
62                         vorbis_info_clear(&tf->vi);
63                         vorbis_comment_clear(&tf->vc);
64                 }
65                 if (tf->vpage)
66                         free(tf->vpage);
67                 if (tf->apage)
68                         free(tf->apage);
69                 delete tf;
70         }
71         if (temp_frame) delete temp_frame;
72         if (stream) close_file();
73         if(pcm_history)
74         {
75                 for(int i = 0; i < asset->channels; i++)
76                         delete [] pcm_history[i];
77                 delete [] pcm_history;
78         }
80         if (flush_lock) delete flush_lock;
83 void FileOGG::get_parameters(BC_WindowBase *parent_window,
84         Asset *asset,
85         BC_WindowBase* &format_window,
86         int audio_options,
87         int video_options)
89         if(audio_options)
90         {
91                 OGGConfigAudio *window = new OGGConfigAudio(parent_window, asset);
92                 format_window = window;
93                 window->create_objects();
94                 window->run_window();
95                 delete window;
96         }
97         else
98         if(video_options)
99         {
100                 OGGConfigVideo *window = new OGGConfigVideo(parent_window, asset);
101                 format_window = window;
102                 window->create_objects();
103                 window->run_window();
104                 delete window;
105         }
108 int FileOGG::reset_parameters_derived()
110         tf = 0;
111         temp_frame = 0;
112         stream = 0;
113         flush_lock = 0;
114         pcm_history = 0;
118 static int read_buffer(FILE *in, sync_window_t *sw, int buflen)
120         char *buffer = ogg_sync_buffer(&sw->sync, buflen);
121 //      printf("reading range: %lli - %lli\n", sw->file_bufpos, sw->file_bufpos + buflen);
122         sw->wlen = fread(buffer, 1, buflen, in);
123         ogg_sync_wrote(&sw->sync, sw->wlen);
124 //      printf("XX data: %c %c %c %c\n", sw->sync.data[0], sw->sync.data[1], sw->sync.data[2], sw->sync.data[3]);
125         sw->file_bufpos += sw->wlen;
126 //      printf("sb: %i\n",buffer);
127         return (sw->wlen);
130 static int read_buffer_at(FILE *in, sync_window_t *sw, int buflen, off_t filepos)
132 //      printf("seeking to %lli %lli\n", filepos, sw->file_bufpos);
133         fseeko(in, filepos, SEEK_SET);
134 //      if (sw->file_bufpos != filepos)
135 //      {
136                 sw->file_bufpos = filepos;
137                 sw->file_pagepos = filepos; // this one is not valid until sync_pageseek!
138                 ogg_sync_reset(&sw->sync);
139                         
140 //      }
141         return read_buffer(in, sw, buflen);
144 static int take_page_out_autoadvance(FILE *in, sync_window_t *sw, ogg_page *og)
146         while (1)
147         {
148                 int ret = ogg_sync_pageout(&sw->sync, og);
149                 if (ret > 0)
150                 {
151 //              printf("fpa: %lli\n", sw->file_pagepos);
152 // advance 'virtual' position
153                         sw->file_pagepos += og->header_len + og->body_len; 
154 //              printf("ret2: %i %i\n",ret, og->header_len + og->body_len); 
155                         return ret;
156                 }
157                 else if (ret < 0)
158                 {
159                         eprintf("FileOGG: Taking page out on nonsynced stream!\n");
160                         return ret;
161                         
162                 } else
163                 {
164                         // need more data for page
165                         if (read_buffer(in, sw, READ_SIZE) == 0) 
166                         {
167 // FIXME We should report that just in some situations... sometimes we go to the end
168 //                              printf("FileOGG: There is no more data in the file we are reading from\n");
169                                 return 0;  // No more data
170                         }
171                 }
172         }
173         return 1;
177 // we never need to autoadvance when syncing, since our read chunks are larger than 
178 // maximum page size
179 static int sync_and_take_page_out(sync_window_t *sw, ogg_page *page)
181         page->header_len = 0;
182         page->body_len = 0;
183         page->header = 0;
184         page->body = 0;
185         int ret = ogg_sync_pageseek(&sw->sync, page);
186         if (ret < 0)
187         {
188                 sw->file_pagepos -= ret;
189         }
190         else if (ret > 0)
191         {
192                 sw->file_pagepos += ret;
193 //              printf("ret: %i %i\n",ret, page->header_len + page->body_len); 
194         }
195         return ret;
199 int FileOGG::open_file(int rd, int wr)
201         this->rd = rd;
202         this->wr = wr;
203         if (!tf)
204         {
205                 tf = new theoraframes_info_t;
206                 tf->audiosync = 0;
207                 tf->videosync = 0;
208         }
211         if(wr)
212         {
215                 if((stream = fopen(asset->path, "w+b")) == 0)
216                 {
217                         eprintf("Error while opening \"%s\" for writing. %m\n", asset->path);
218                         return 1;
219                 }
221                 tf->audio_bytesout = 0;
222                 tf->video_bytesout = 0;
223                 tf->videotime = 0;
224                 tf->audiotime = 0;
226                 tf->vpage_valid = 0;
227                 tf->apage_valid = 0;
228                 tf->apage_buffer_length = 0;
229                 tf->vpage_buffer_length = 0;
230                 tf->apage = NULL;
231                 tf->vpage = NULL;
232                 tf->v_pkg=0;
233                 tf->a_pkg=0;
236                 /* yayness.  Set up Ogg output stream */
237                 srand (time (NULL));
239                 if(asset->video_data)
240                 {
241                         ogg_stream_init (&tf->to, rand ());    /* oops, add one ot the above */
242                 
243                         theora_info_init (&tf->ti);
244                         
245                         tf->ti.frame_width = asset->width; 
246                         tf->ti.frame_height = asset->height;
247                         
248                         tf->ti.width = ((asset->width + 15) >>4)<<4; // round up to the nearest multiple of 16 
249                         tf->ti.height = ((asset->height + 15) >>4)<<4; // round up to the nearest multiple of 16
250                         if (tf->ti.width != tf->ti.frame_width || tf->ti.height != tf->ti.frame_height)
251                         {
252                                 eprintf("WARNING: Encoding theora when width or height are not dividable by 16 is suboptimal\n");
253                         }
254                         
255                         tf->ti.offset_x = 0;
256                         tf->ti.offset_y = tf->ti.height - tf->ti.frame_height;
257                         tf->ti.fps_numerator = (unsigned int)(asset->frame_rate * 1000000);
258                         tf->ti.fps_denominator = 1000000;
259                         
260                         if (asset->aspect_ratio > 0)
261                         {
262                                 // Cinelerra uses frame aspect ratio, theora uses pixel aspect ratio
263                                 float pixel_aspect = asset->aspect_ratio / asset->width * asset->height;
264                                 tf->ti.aspect_numerator = (unsigned int)(pixel_aspect * 1000000);
265                                 tf->ti.aspect_denominator = 1000000;
266                         } else
267                         {
268                                 tf->ti.aspect_numerator = 1000000;
269                                 tf->ti.aspect_denominator = 1000000;
270                         }
271                         if(EQUIV(asset->frame_rate, 25) || EQUIV(asset->frame_rate, 50))
272                                 tf->ti.colorspace = OC_CS_ITU_REC_470BG;
273                         else if((asset->frame_rate > 29 && asset->frame_rate < 31) || (asset->frame_rate > 59 && asset->frame_rate < 61) )
274                                 tf->ti.colorspace = OC_CS_ITU_REC_470M;
275                         else
276                                 tf->ti.colorspace = OC_CS_UNSPECIFIED;
278                         if (asset->theora_fix_bitrate)
279                         {
280                                 tf->ti.target_bitrate = asset->theora_bitrate; 
281                                 tf->ti.quality = 0;
282                         } else
283                         {
284                                 tf->ti.target_bitrate = 0;
285                                 tf->ti.quality = asset->theora_quality;     // video quality 0-63
286                         }
287                         tf->ti.dropframes_p = 0;
288                         tf->ti.quick_p = 1;
289                         tf->ti.keyframe_auto_p = 1;
290                         tf->ti.keyframe_frequency = asset->theora_keyframe_frequency;
291                         tf->ti.keyframe_frequency_force = asset->theora_keyframe_force_frequency;
292                         tf->ti.keyframe_data_target_bitrate = (unsigned int) (tf->ti.target_bitrate * 1.5) ;
293                         tf->ti.keyframe_auto_threshold = 80;
294                         tf->ti.keyframe_mindistance = 8;
295                         tf->ti.noise_sensitivity = 1;           
296                         tf->ti.sharpness = 2;
297                         
298                                         
299                         if (theora_encode_init (&tf->td, &tf->ti))
300                         {
301                                 eprintf("(FileOGG:file_open) initialization of theora codec failed\n");
302                         }
303                 }
304                 /* init theora done */
306                 /* initialize Vorbis too, if we have audio. */
307                 if(asset->audio_data)
308                 {
309                         ogg_stream_init (&tf->vo, rand ());    
310                         vorbis_info_init (&tf->vi);
311                         /* Encoding using a VBR quality mode.  */
312                         int ret;
313                         if(!asset->vorbis_vbr) 
314                         {
315                                 ret = vorbis_encode_init(&tf->vi, 
316                                                         asset->channels, 
317                                                         asset->sample_rate, 
318                                                         asset->vorbis_max_bitrate, 
319                                                         asset->vorbis_bitrate,
320                                                         asset->vorbis_min_bitrate); 
321                         } else
322                         {
323                                 // Set true VBR as demonstrated by http://svn.xiph.org/trunk/vorbis/doc/vorbisenc/examples.html
324                                 ret = vorbis_encode_setup_managed(&tf->vi,
325                                         asset->channels, 
326                                         asset->sample_rate, 
327                                         -1, 
328                                         asset->vorbis_bitrate, 
329                                         -1);
330                                 ret |= vorbis_encode_ctl(&tf->vi, OV_ECTL_RATEMANAGE_AVG, NULL);
331                                 ret |= vorbis_encode_setup_init(&tf->vi);
332                         }
334                         if (ret)
335                         {
336                                 eprintf("The Vorbis encoder could not set up a mode according to\n"
337                                                         "the requested quality or bitrate.\n\n");
339                                 fclose (stream);
340                                 stream = 0;
341                                 return 1;
342                         }
344                         vorbis_comment_init (&tf->vc); // comment is cleared lateron 
345                         vorbis_comment_add_tag (&tf->vc, "ENCODER", PACKAGE_STRING);
346                         /* set up the analysis state and auxiliary encoding storage */
347                         vorbis_analysis_init (&tf->vd, &tf->vi);
348                         vorbis_block_init (&tf->vd, &tf->vb);
350                 }
351                 /* audio init done */
353                 /* write the bitstream header packets with proper page interleave */
355                 /* first packet will get its own page automatically */
356                 if(asset->video_data)
357                 {
358                         theora_encode_header (&tf->td, &tf->op);
359                         ogg_stream_packetin (&tf->to, &tf->op);
360                         if (ogg_stream_pageout (&tf->to, &tf->og) != 1)
361                         {
362                                 eprintf("Internal Ogg library error.\n");
363                                 return 1;
364                         }
365                         fwrite (tf->og.header, 1, tf->og.header_len, stream);
366                         fwrite (tf->og.body, 1, tf->og.body_len, stream);
368                         /* create the remaining theora headers */
369                         theora_comment_init (&tf->tc);
370                         theora_comment_add_tag (&tf->tc, "ENCODER", PACKAGE_STRING);
371                         theora_encode_comment (&tf->tc, &tf->op);
372                         ogg_stream_packetin (&tf->to, &tf->op);
373                         theora_comment_clear(&tf->tc);
374                         theora_encode_tables (&tf->td, &tf->op);
375                         ogg_stream_packetin (&tf->to, &tf->op);
376                 }
377                 if(asset->audio_data)
378                 {
379                         ogg_packet header;
380                         ogg_packet header_comm;
381                         ogg_packet header_code;
383                         vorbis_analysis_headerout (&tf->vd, &tf->vc, &header,
384                                        &header_comm, &header_code);
385                         ogg_stream_packetin (&tf->vo, &header);    /* automatically placed in its own page */
386                         vorbis_comment_clear(&tf->vc);
387                         if (ogg_stream_pageout (&tf->vo, &tf->og) != 1)
388                         {
389                                 eprintf("Internal Ogg library error.\n");
390                                 return 1;
391                         }
392                         fwrite (tf->og.header, 1, tf->og.header_len, stream);
393                         fwrite (tf->og.body, 1, tf->og.body_len, stream);
395                         /* remaining vorbis header packets */
396                         ogg_stream_packetin (&tf->vo, &header_comm);
397                         ogg_stream_packetin (&tf->vo, &header_code);
398                 }
400                 /* Flush the rest of our headers. This ensures
401                  * the actual data in each stream will start
402                  * on a new page, as per spec. */
403                 while (1 && asset->video_data)
404                 {
405                         int result = ogg_stream_flush (&tf->to, &tf->og);
406                         if (result < 0)
407                         {
408                                 /* can't get here */
409                                 eprintf("Internal Ogg library error.\n");
410                                 return 1;
411                         }
412                         if (result == 0)
413                                 break;
414                         fwrite (tf->og.header, 1, tf->og.header_len, stream);
415                         fwrite (tf->og.body, 1, tf->og.body_len, stream);
416                 }
417                 while (1 && asset->audio_data)
418                 {
419                         int result = ogg_stream_flush (&tf->vo, &tf->og);
420                         if (result < 0)
421                         {
422                                 /* can't get here */
423                                 eprintf("Internal Ogg library error.\n");
424                                 return 1;
425                         }
426                         if (result == 0)
427                                 break;
428                         fwrite (tf->og.header, 1, tf->og.header_len, stream);
429                         fwrite (tf->og.body, 1, tf->og.body_len, stream);
430                 }
431                 flush_lock = new Mutex("OGGFile::Flush lock");
432 //              printf("End of headers at position: %lli\n", ftello(stream));
433         } else
434         if (rd)
435         {
437                 if((stream = fopen(asset->path, "rb")) == 0)
438                 {
439                         eprintf("Error while opening %s for reading. %m\n", asset->path);
440                         return 1;
441                 }
443                 /* get file length */
444                 struct stat file_stat;
445                 stat(asset->path, &file_stat);
446                 file_length = file_stat.st_size;
448                 /* start up Ogg stream synchronization layer */
449                 /* oy is used just here to parse header, we use separate syncs for video and audio*/
450                 sync_window_t oy;
451                 ogg_sync_init(&oy.sync);
452                 // make sure we init the position structures to zero
453                 read_buffer_at(stream, &oy, READ_SIZE, 0);
456                 /* init supporting Vorbis structures needed in header parsing */
457                 vorbis_info_init(&tf->vi);
458                 vorbis_comment_init(&tf->vc);
461                 /* init supporting Theora structures needed in header parsing */
462                 theora_comment_init(&tf->tc);
463                 theora_info_init(&tf->ti);
467                 /* Ogg file open; parse the headers */
468                 /* Only interested in Vorbis/Theora streams */
469                 int stateflag = 0;
470                 int theora_p = 0;
471                 int vorbis_p = 0;
472                 while(!stateflag)
473                 {
476 //                      int ret = read_buffer(stream, &oy, 4096);
477                         TRACE("FileOGG::open_file 60")
478 //                      if(ret == 0)
479 //                              break;
480                         
481                         while(take_page_out_autoadvance(stream, &oy, &tf->og) > 0)
482                         {
483                                 ogg_stream_state test;
485                                 /* is this a mandated initial header? If not, stop parsing */
486                                 if(!ogg_page_bos(&tf->og))
487                                 {
488                                         /* don't leak the page; get it into the appropriate stream */
489                                 //      queue_page(&tf->og);
490                                         if(theora_p)ogg_stream_pagein(&tf->to, &tf->og);
491                                         if(vorbis_p)ogg_stream_pagein(&tf->vo, &tf->og);
492                                 
493                                         stateflag = 1;
494                                         break;
495                                 }
497                                 ogg_stream_init(&test, ogg_page_serialno(&tf->og));
498                                 ogg_stream_pagein(&test, &tf->og);
499                                 ogg_stream_packetout(&test, &tf->op);
501                                 /* identify the codec: try theora */
502                                 if(!theora_p && theora_decode_header(&tf->ti, &tf->tc, &tf->op)>=0)
503                                 {
504                                         /* it is theora */
505                                         memcpy(&tf->to, &test, sizeof(test));
506                                         theora_p = 1;
507         // find out granule shift - from liboggz's oggz_auto.c
508                                         unsigned char * header = tf->op.packet;
509                                         theora_keyframe_granule_shift = (char) ((header[40] & 0x03) << 3);
510                                         theora_keyframe_granule_shift |= (header[41] & 0xe0) >> 5;
512                                 } else if(!vorbis_p && vorbis_synthesis_headerin(&tf->vi, &tf->vc, &tf->op)>=0)
513                                 {
514                                         /* it is vorbis */
515                                         memcpy(&tf->vo, &test, sizeof(test));
516                                         vorbis_p = 1;
517                                 } else 
518                                 {
519                                         /* whatever it is, we don't care about it */
520                                         ogg_stream_clear(&test);
521                                 }
522                         }
523                 /* fall through to non-bos page parsing */
524                 }
526                 
527                 /* we're expecting more header packets. */
528                 while((theora_p && theora_p < 3) || (vorbis_p && vorbis_p < 3))
529                 {
530                         int ret;
532                         /* look for further theora headers */
533                         while(theora_p && (theora_p < 3) && (ret = ogg_stream_packetout(&tf->to, &tf->op)))
534                         {
535                                 if(ret < 0)
536                                 {
537                                         eprintf("Error parsing Theora stream headers; corrupt stream?\n");
538                                         return 1;
539                                 }
540                                 if(theora_decode_header(&tf->ti, &tf->tc, &tf->op))
541                                 {
542                                         eprintf("Error parsing Theora stream headers; corrupt stream?\n");
543                                         return 1;
544                                 }
545                                 theora_p++;
546                                 if(theora_p == 3) 
547                                         break;
548                         }
550                         /* look for more vorbis header packets */
551                         while(vorbis_p && (vorbis_p < 3) && (ret = ogg_stream_packetout(&tf->vo, &tf->op)))
552                         {
553                                 if(ret<0)
554                                 {
555                                         eprintf("Error parsing Vorbis stream headers; corrupt stream?\n");
556                                         return 1;
557                                 }
558                                 if (vorbis_synthesis_headerin(&tf->vi, &tf->vc, &tf->op))
559                                 {
560                                         eprintf("Error parsing Vorbis stream headers; corrupt stream?\n");
561                                         return 1;
562                                 }
563                                 vorbis_p++;
564                                 if (vorbis_p == 3)
565                                         break;
566                         }
568                         if ((!vorbis_p || vorbis_p == 3) && (!theora_p || theora_p == 3)) 
569                                 break;
570                         /* The header pages/packets will arrive before anything else we
571                             care about, or the stream is not obeying spec */
573                         if(take_page_out_autoadvance(stream, &oy, &tf->og) > 0)
574                         {
575 //                              queue_page(&tf->og); /* demux into the appropriate stream */
576                                 if(theora_p) ogg_stream_pagein(&tf->to, &tf->og);
577                                 if(vorbis_p) ogg_stream_pagein(&tf->vo, &tf->og);
579                         } else
580                         {
581                                 eprintf("End of file while searching for codec headers.\n");
582                                 return 1;
583                         }
584                 }
585                 // Remember where the real data begins for later seeking purposes
586                 filedata_begin = oy.file_pagepos; 
590                 /* and now we have it all.  initialize decoders */
591                 if(theora_p)
592                 {
593                         int ret;
595 // WORKAROUND for bug in alpha4 version of theora:
596                         tf->td.internal_encode = 0;
598                         ret = theora_decode_init(&tf->td, &tf->ti);
599                         double fps = (double)tf->ti.fps_numerator/tf->ti.fps_denominator;
600 /*                      printf("FileOGG: Ogg logical stream %x is Theora %dx%d %.02f fps\n",
601                                 (unsigned int)tf->to.serialno, tf->ti.width, tf->ti.height, 
602                                 fps);
605 Not yet available in alpha4, we assume 420 for now
607                         switch(tf->ti.pixelformat)
608                         {
609                                 case OC_PF_420: printf(" 4:2:0 video\n"); break;
610                                 case OC_PF_422: printf(" 4:2:2 video\n"); break;
611                                 case OC_PF_444: printf(" 4:4:4 video\n"); break;
612                                 case OC_PF_RSVD:
613                                 default:
614                                         printf(" video\n  (UNKNOWN Chroma sampling!)\n");
615                                 break;
616                         }
619                         theora_cmodel = BC_YUV420P;
620                         
621                         if(tf->ti.width!=tf->ti.frame_width || tf->ti.height!=tf->ti.frame_height)
622                         {
623                                 eprintf("Frame content is %dx%d with offset (%d,%d), We do not support this yet. You will get black border.\n",
624                                                         tf->ti.frame_width, tf->ti.frame_height, tf->ti.offset_x, tf->ti.offset_y);
625                         }
626                         tf->videosync = new sync_window_t;
627                         ogg_sync_init(&tf->videosync->sync);
628                         tf->videosync->wlen = 0;
630                         ret = ogg_get_first_page(tf->videosync, tf->to.serialno, &tf->videopage);
631                         ogg_packet op;
633                         // we have headers already decoded, so just skip them
634                         ogg_stream_reset(&tf->to);
635                         ogg_stream_pagein(&tf->to, &tf->videopage);
636                         while (1)
637                         {
638                                 while (ogg_stream_packetpeek(&tf->to, NULL) != 1)
639                                 {
640                                         if (!ogg_get_next_page(tf->videosync, tf->to.serialno, &tf->videopage))
641                                         {
642                                                 eprintf("Cannot find next page while looking for first non-header packet\n");
643                                                 return 1;
644                                         }
645                                         ogg_stream_pagein(&tf->to, &tf->videopage);
646                                 }
647                                 ogg_stream_packetout(&tf->to, &op);
648                                 if (!theora_packet_isheader(&op))
649                                         break;
650                         }
651                         // now get to the page of the finish of the first packet
652                         while (ogg_page_packets(&tf->videopage) == 0) 
653                         {
654                                 if (ogg_page_granulepos(&tf->videopage) != -1)
655                                 {
656                                         eprintf("Broken ogg file - broken page: ogg_page_packets == 0 and granulepos != -1\n");
657                                         return 1;
658                                 }
659                                 ogg_get_next_page(tf->videosync, tf->to.serialno, &tf->videopage);
660                         }
661                         // FIXME - LOW PRIORITY - start counting at first decodable keyframe!
662                         // but then we have to fix a/v sync somehow
663                         start_frame = (int64_t) (theora_granule_frame (&tf->td, ogg_page_granulepos(&tf->videopage)) - ogg_page_packets(&tf->videopage)) + 1;
665                         ret = ogg_get_last_page(tf->videosync, tf->to.serialno, &tf->videopage);
666                         last_frame = (int64_t) (theora_granule_frame (&tf->td, ogg_page_granulepos(&tf->videopage)));
667                         asset->video_length = last_frame - start_frame + 1;
668 //                      printf("FileOGG:: first frame: %lli, last frame: %lli, video length: %lli\n", start_frame, last_frame, asset->video_length);
669                         
670                         asset->layers = 1;
671                         // FIXME - LOW PRIORITY Cinelerra does not honor the frame_width and frame_height
672                         asset->width = tf->ti.width;
673                         asset->height = tf->ti.height;
674 // Don't want a user configured frame rate to get destroyed
675                         if(!asset->frame_rate)
676                                 asset->frame_rate = fps;
677 // All theora material is noninterlaced by definition
678                         if(!asset->interlace_mode)
679                                 asset->interlace_mode = BC_ILACE_MODE_NOTINTERLACED;
681         /*              ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 0 +start_frame);
682                         ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 1 +start_frame);
683                         ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 5 +start_frame);
684                         ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 206 +start_frame);
685                         ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 207 +start_frame);
686                         ogg_get_page_of_frame(tf->videosync, tf->to.serialno, &og, 208 +start_frame);
688                         int64_t kf;
689                         ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, 0 + start_frame, &kf);
690                         ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, 1 + start_frame, &kf);
691                         ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, 5 + start_frame, &kf);
692                         ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, 66 + start_frame, &kf);
693                         //printf("Keyframe: %lli\n", kf);
694                         ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, 1274 + start_frame, &kf);
696         
697                         set_video_position(0); // make sure seeking is done to the first sample
698                         ogg_frame_position = -10;
699                         asset->video_data = 1;
700                         strncpy(asset->vcodec, "theo", 4);
703 //                  report_colorspace(&ti);
704 //                  dump_comments(&tc);
705                 } else 
706                 {
707                         /* tear down the partial theora setup */
708                         theora_info_clear(&tf->ti);
709                         theora_comment_clear(&tf->tc);
710                 }
713                 if(vorbis_p)
714                 {
715                         vorbis_synthesis_init(&tf->vd, &tf->vi);
716                         vorbis_block_init(&tf->vd, &tf->vb);
717 /*                      fprintf(stderr,"FileOGG: Ogg logical stream %x is Vorbis %d channel %d Hz audio.\n",
718                                 (unsigned int)tf->vo.serialno, tf->vi.channels, (int)tf->vi.rate);
719 */                      
720                         /* init audio_sync structure */
721                         tf->audiosync = new sync_window_t;
722                         ogg_sync_init(&tf->audiosync->sync);
723                         tf->audiosync->wlen = 0;
725                         int ret2 = ogg_get_first_page(tf->audiosync, tf->vo.serialno, &tf->audiopage);
726                         int result;
727                         ogg_packet op;
728                         ogg_stream_reset(&tf->vo);
729                         // FIXME - LOW PRIORITY should be getting pages until one has granulepos, probably never happens in pracitce
730                         ogg_stream_pagein(&tf->vo, &tf->audiopage);
731                         ogg_int64_t accumulated = 0;
732                         long        lastblock = -1;
733                         while((result = ogg_stream_packetout(&tf->vo, &op)))
734                         {
735                                 if(result > 0)
736                                 { // ignore holes 
737                                         long thisblock =  vorbis_packet_blocksize(&tf->vi, &op);
738                                         if(lastblock != -1)
739                                                 accumulated += (lastblock + thisblock) >> 2;
740                                         lastblock = thisblock;
741                                 }
742                         }
743                         start_sample = ogg_page_granulepos(&tf->audiopage) - accumulated;
745                         printf("Begin: %lli, To byte: %lli,  granule: %lli, serialno: %x\n", 
746                                         tf->audiosync->file_pagepos_found,
747                                         tf->audiosync->file_pagepos_found + tf->audiopage.body_len + tf->audiopage.header_len,
748                                         ogg_page_granulepos(&tf->audiopage), 
749                                         ogg_page_serialno(&tf->audiopage));
750                         while (ogg_get_next_page(tf->audiosync, tf->vo.serialno, &tf->audiopage))
751                                 printf("At byte: %lli, To byte: %lli,  granule: %lli, serialno: %x\n", 
752                                         tf->audiosync->file_pagepos_found,
753                                         tf->audiosync->file_pagepos_found + tf->audiopage.body_len + tf->audiopage.header_len,
754                                         ogg_page_granulepos(&tf->audiopage), 
755                                         ogg_page_serialno(&tf->audiopage));
758                         int ret = ogg_get_last_page(tf->audiosync, tf->vo.serialno, &tf->audiopage);
759                         last_sample = ogg_page_granulepos(&tf->audiopage);
760                         asset->audio_length = last_sample - start_sample;
761                                                 
762 /*                      printf("FileOGG:: First sample: %lli, last_sample: %lli\n", start_sample, last_sample);
763                         printf("FileOGG:: audio length: samples: %lli, playing time: %f\n", asset->audio_length, 1.0 * asset->audio_length / tf->vi.rate);
764 */                      
765 /*                      printf("End: %lli, To byte: %lli,  granule: %lli, serialno: %x\n", 
766                                         tf->audiosync->file_pagepos_found,
767                                         tf->audiosync->file_pagepos_found + tf->audiopage.body_len + tf->audiopage.header_len,
768                                         ogg_page_granulepos(&tf->audiopage), 
769                                         ogg_page_serialno(&tf->audiopage));
770                         while (ogg_get_prev_page(tf->audiosync, tf->vo.serialno, &tf->audiopage))
771                                 printf("At byte: %lli, To byte: %lli,  granule: %lli, serialno: %x\n", 
772                                         tf->audiosync->file_pagepos_found,
773                                         tf->audiosync->file_pagepos_found + tf->audiopage.body_len + tf->audiopage.header_len,
774                                         ogg_page_granulepos(&tf->audiopage), 
775                                         ogg_page_serialno(&tf->audiopage));
777                         
778 /*                      ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 0);
779                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 1);
780                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 50);
781                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 5000);
782                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 30000);
783                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 50000);
784                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 90000);
785                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 95999);
786                         ogg_get_page_of_sample(tf->audiosync, tf->vo.serialno, &tf->audiopage, 96000);
787                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 0);
788                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 1);
789                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 5000);
790                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 30000);
791                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 50000);
792                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 90000);
793                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 95999);
794                         ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, 96000);
795 */                      
796                         asset->channels = tf->vi.channels;
797                         if(!asset->sample_rate)
798                                 asset->sample_rate = tf->vi.rate;
799                         asset->audio_data = 1;
800                         
802                         ogg_sample_position = -10;
803                         set_audio_position(0); // make sure seeking is done to the first sample
804                         strncpy(asset->acodec, "vorb", 4);
807                 } else 
808                 {
809                         /* tear down the partial vorbis setup */
810                         vorbis_info_clear(&tf->vi);
811                         vorbis_comment_clear(&tf->vc);
812                 }
814                 ogg_sync_clear(&oy.sync);
816         }
817         return 0;
820 int FileOGG::ogg_get_prev_page(sync_window_t *sw, long serialno, ogg_page *og)
822         char *buffer;
823         ogg_page page;
824         off_t filepos = sw->file_pagepos_found - READ_SIZE;
825         int first_page_offset = 0;
826         int done = 0;   
827         int read_len = READ_SIZE;
829 //      printf("fp: %lli pagepos found: %lli\n", filepos, sw->file_pagepos_found);
830         while (!done)
831         {
832                 if (filepos < 0)
833                 {
834 //                      read_len = read_len - (filedata_begin - filepos);
835                         read_len = read_len + filepos;
836                         filepos = 0;
837                 }
838                 if (read_len <= 0) 
839                         return 0;
840                 int have_read = read_buffer_at(stream, sw, read_len, filepos);
841                 
842 //              printf("reading at %lli, len: %i, read: %i, pagepos: %lli, pageposfound: %lli\n", filepos, read_len, have_read, sw->file_pagepos, sw->file_pagepos_found);
843 //              printf("Buffer position: %lli\n", sw->file_bufpos);
844 //              printf("SS: storage: %i, fill: %i, returned: %i\n", sw->sync.storage, sw->sync.fill, sw->sync.returned);
845 //              printf("US: unsynced%i, headrebytes: %i, bodybyes: %i\n", sw->sync.unsynced, sw->sync.headerbytes, sw->sync.bodybytes);
846 //              printf("data: %c %c %c %c\n", sw->sync.data[0], sw->sync.data[1], sw->sync.data[2], sw->sync.data[3]);
847                 if (!have_read) 
848                         return 0;
849                 
850 // read all pages in the buffer
851                 int page_offset = 0;
852                 int page_length = 0;
853                 int first_page = 1;
854                 while (first_page || page_length) 
855                 {
856                         // if negative, skip bytes
857                         while ((page_length = sync_and_take_page_out(sw, &page)) < 0)
858                         {
859                                 page_offset -= page_length;
860                                                 
861 //                              if (filepos == 0)
862 //                                      printf("BBBb page_len: %i\n", page_length);
863                         }
864 //                      if (filepos == 0 && page_length)
865 //                      {
866 //                              printf("AAAAAAAAAAAAAAAAAAAAAAAAAaaa\n");
867 //                              printf("pp: %lli %x\n", sw->file_pagepos, ogg_page_serialno(&page));
868 //                      }
869                         if (first_page)
870                                 first_page_offset = page_offset;
871                         first_page = 0;
872 //                      printf("pl: %i, serial: %x iscem: %x\n", page_length, ogg_page_serialno(&page), serialno);
873                         if (page_length && ogg_page_serialno(&page) == serialno)
874                         {
875                                 // we will copy every page until last page in this buffer
876                                 done = 1;
877                                 
878                                 sw->file_pagepos_found = sw->file_pagepos - page.header_len - page.body_len;
879 //                              printf("got it : %lli %i %i\n", sw->file_pagepos, page.header_len, page.body_len);
880                                 memcpy(og, &page, sizeof(page));
881                         }
882                 }
883                 off_t old_filepos = filepos;
884 //              printf("fpo: %i\n", first_page_offset);
885                 filepos = filepos + first_page_offset - READ_SIZE;
886         }
887         
888 //      printf("finished\n");
889         if (done) 
890                 return 1;
891         else 
892                 return 0;
895 int FileOGG::ogg_get_last_page(sync_window_t *sw, long serialno, ogg_page *og)
897         char *buffer;
898         ogg_page page;
899         off_t filepos = file_length - READ_SIZE;
900         if (filepos < 0) 
901                 filepos = 0;
903         int first_page_offset = 0;
904         int done = 0;   
905         while (!done && filepos >= 0)
906         {
907                 int readlen;
908                 readlen = read_buffer_at(stream, sw, READ_SIZE, filepos);
910 // read all pages in the buffer
911                 int page_offset = 0;
912                 int page_length = 0;
913                 int first_page = 1;
914                 while (first_page || page_length) 
915                 {
916                         // if negative, skip bytes
917                         while ((page_length = sync_and_take_page_out(sw, &page)) < 0)
918                                         page_offset -= page_length;
919                         if (first_page)
920                                 first_page_offset = page_offset;
921                         first_page = 0;
922                         if (page_length && ogg_page_serialno(&page) == serialno)
923                         {
924                                 // we will copy every page until last page in this buffer
925                                 done = 1;
926                                 sw->file_pagepos_found = sw->file_pagepos - page.header_len - page.body_len;
927                                 memcpy(og, &page, sizeof(page));
928                         }
929                 }
930                 filepos = filepos + first_page_offset - READ_SIZE;              
931         }
932         
933         if (done) 
934                 return 1;
935         else 
936                 return 0;
939 int FileOGG::ogg_get_first_page(sync_window_t *sw, long serialno, ogg_page *og)
941 //      printf("FileOGG:: Seeking to first page at %lli\n", filedata_begin);
942         read_buffer_at(stream, sw, READ_SIZE, 0);
943 // we don't even need to sync since we _know_ it is right
944         return (ogg_get_next_page(sw, serialno, og));
947 int FileOGG::ogg_seek_to_databegin(sync_window_t *sw, long serialno)
949         
950 //      printf("FileOGG:: Seeking to first page at %lli\n", filedata_begin);
951         read_buffer_at(stream, sw, READ_SIZE, filedata_begin);
952 // we don't even need to sync since we _know_ it is right
953         return (0);
956 int FileOGG::ogg_get_next_page(sync_window_t *sw, long serialno, ogg_page *og)
958         while (take_page_out_autoadvance(stream, sw, og) > 0)
959         { 
960                 if (ogg_page_serialno(og) == serialno)
961                 {
962                         sw->file_pagepos_found = sw->file_pagepos - og->header_len - og->body_len;
963                         return 1;
964                 }
965         }
966         return 0;
969 int FileOGG::ogg_sync_and_get_next_page(sync_window_t *sw, long serialno, ogg_page *og)
971 // TODO: Put better error reporting inhere
972         int ret;
973         while ((ret = sync_and_take_page_out(sw, og)) < 0)
974         {
975                 // do nothing;
976         }
977         if (ret == 0) 
978                 return 0;
979         if (ogg_page_serialno(og) == serialno)
980         {
981                 sw->file_pagepos_found = sw->file_pagepos - og->header_len - og->body_len;
982                 return 1;
983         }
984         while (ogg_get_next_page(sw, serialno, og))
985                 if (ogg_page_serialno(og) == serialno)
986                 {
987                         sw->file_pagepos_found = sw->file_pagepos - og->header_len - og->body_len;
988                         return 1;
989                 }
990         
991         return 0;
993 // Returns:
994 // >= 0, number of sample within a page
995 // <  0 error
996 int FileOGG::ogg_get_page_of_sample(sync_window_t *sw, long serialno, ogg_page *og, int64_t sample)
998 // First make an educated guess about position
999         if (sample >= asset->audio_length + start_sample)
1000         {
1001                 eprintf("Illegal seek beyond end of samples\n");
1002                 return 0;
1003         }
1004         off_t educated_guess = filedata_begin + (file_length - filedata_begin) * (sample - start_sample) / asset->audio_length - READ_SIZE;
1005         if (educated_guess < 0) 
1006                 educated_guess = 0;
1007 //      printf("My educated guess: %lli\n", educated_guess); 
1008 // now see if we won
1009         read_buffer_at(stream, sw, READ_SIZE, educated_guess);
1010         ogg_sync_and_get_next_page(sw, serialno, og);
1011         int64_t end_sample = ogg_page_granulepos(og);
1012         // linear seek to the sample
1013         int64_t start_sample = 0;
1014 // TODO: Use bisection also
1015 //      printf("Next page granulepos: %lli, pagepos: %lli\n", end_sample, sw->file_pagepos_found);
1016         if (end_sample <= sample)
1017         {
1018         // scan forward
1019                 while (end_sample <= sample)
1020                 {
1021                         ogg_get_next_page(sw, serialno, og); 
1022                         start_sample = end_sample;
1023                         end_sample = ogg_page_granulepos(og);
1024                 }
1025                 ogg_get_prev_page(sw, serialno, og);
1026                 while (ogg_page_continued(og) && ogg_page_packets(og) == 1)
1027                         ogg_get_prev_page(sw, serialno, og);
1028         } else
1029         {
1030         // scan backward
1031                 start_sample = end_sample;
1032                 while (start_sample > sample || (ogg_page_continued(og) && 
1033                         ogg_page_packets(og) == 1))
1034                 {
1035 //                      printf("get prev page: %lli pagepos:%lli\n", ogg_page_granulepos(og), sw->file_pagepos_found);
1036                         ogg_get_prev_page(sw, serialno, og);
1037                         end_sample = start_sample;
1038                         start_sample = ogg_page_granulepos(og);
1039                 }
1040         // go forward one page at the end
1042         }
1043         
1044 //      printf("For sample %lli we need to start decoding on page with granulepos: %lli\n", sample, ogg_page_granulepos(og));
1045         return 1;
1048 // seeks, so next sample returned will be the correct one
1049 // sample here is still the vorbis sample number (= cinelerra sample number + start_sample)
1050 // reinits the decoding engine
1052 int FileOGG::ogg_seek_to_sample(sync_window_t *sw, long serialno, int64_t sample)
1054         // MAYBE FIXME - find out if we really are decoding previous two packets or not
1055         // get to the sample
1056         ogg_page og;
1057         ogg_packet op;
1058 //      printf("Calling get page of sample\n");
1059         if (!ogg_get_page_of_sample(sw, serialno, &og, sample))
1060         {
1061                 eprintf("Seeking to sample's page failed\n");
1063                 return 0;
1064         }
1065 //      printf("Pagepos: %lli\n", sw->file_pagepos);
1066         vorbis_synthesis_restart(&tf->vd);
1067         ogg_stream_reset(&tf->vo);
1068         ogg_stream_pagein(&tf->vo, &og);
1069         int sync = 0;
1070 //      printf("seeking to sample : %lli , starting at page with gpos: %lli\n", sample, ogg_page_granulepos(&og));
1071         
1072         int64_t current_comming_sample = -1;
1073         while (1) 
1074         {
1075         
1076                 // make sure we have a packet ready
1077                 while (ogg_stream_packetpeek(&tf->vo, NULL) != 1)
1078                 {
1079                         if (!ogg_get_next_page(sw, serialno, &og))
1080                         {
1081                                 eprintf("Cannot find next page while seeking\n");
1082                                 return 0;
1083                         }
1084                         ogg_stream_pagein(&tf->vo, &og);
1085                 }
1086                 ogg_stream_packetout(&tf->vo, &op);
1087                 if (sync)
1088                 {
1089                         
1090                         if(!vorbis_synthesis(&tf->vb, &op))
1091                         {
1092                                 int ret= vorbis_synthesis_blockin(&tf->vd, &tf->vb);
1093                                 int64_t previous_comming_sample = current_comming_sample;
1094                                 current_comming_sample += vorbis_synthesis_pcmout(&tf->vd, NULL);
1095                                 if (current_comming_sample > sample)
1096                                 {
1097                                         if (previous_comming_sample > sample)
1098                                         {
1099                                                 eprintf("Ogg decoding error while seeking sample\n");
1100                                         }
1101                                         vorbis_synthesis_read(&tf->vd, (sample - previous_comming_sample));
1102 //                                      printf("WE GOT IT, samples already decoded: %li\n", vorbis_synthesis_pcmout(&tf->vd,NULL));
1103                                         return 1; // YAY next sample read is going to be ours, sexy!
1104                                 } else
1105                                 {
1106                                         // discard decoded data before current sample
1107                                         vorbis_synthesis_read(&tf->vd, (current_comming_sample - previous_comming_sample));
1108                                         
1109                                 }
1110                         }
1111                 }
1112                 if (!sync && op.granulepos >= 0)
1113                 {
1114                         sync = 1;
1115                         current_comming_sample = op.granulepos;
1116                         if(!vorbis_synthesis(&tf->vb, &op))
1117                         {
1118                                 vorbis_synthesis_blockin(&tf->vd, &tf->vb);
1119                                 if (vorbis_synthesis_pcmout(&tf->vd, NULL) != 0)
1120                                 {
1121                                         eprintf("Something wrong while trying to seek\n");
1122                                         return 0;
1123                                 }
1124                         
1125                         }
1126                         
1127                 }
1128         }
1129         
1130         
1131         return 0;
1134 int FileOGG::ogg_get_page_of_frame(sync_window_t *sw, long serialno, ogg_page *og, int64_t frame)
1136         if (frame >= asset->video_length + start_frame)
1137         {
1138                 eprintf("Illegal seek beyond end of frames\n");
1139                 return 0;
1140         }
1141 //      printf("frame: %lli start frame: %lli\n", frame, start_frame);
1142 //      printf("file_length: %lli filedata_begin: %lli\n", file_length, filedata_begin);
1143         off_t educated_guess = filedata_begin + (file_length - filedata_begin) * (frame - start_frame) / asset->video_length - READ_SIZE/2;
1144 //      educated_guess += 100000;
1145         if (educated_guess > file_length - READ_SIZE)
1146                 educated_guess = file_length - READ_SIZE;
1147         if (educated_guess < filedata_begin) 
1148                 educated_guess = filedata_begin;
1149 //      printf("My educated guess: %lli\n", educated_guess); 
1150 // now see if we won
1151         read_buffer_at(stream, sw, READ_SIZE, educated_guess);
1152         ogg_sync_and_get_next_page(sw, serialno, og);
1153         int64_t pageend_frame;
1154         int read_back = 0;
1155         // find the page with "real" ending
1156         while ((pageend_frame = ogg_page_granulepos(og)) == -1)
1157         {
1158                 if (ogg_get_next_page(sw, serialno, og) == 0) 
1159                 {
1160                         read_back = 1;
1161                         break;
1162                 } 
1163         }
1164         pageend_frame = theora_granule_frame(&tf->td, ogg_page_granulepos(og));
1166         // FIXME - MEDIUM PRIORITY: read back if we've gone too far and no page of our serialno at all can be found
1168         
1169         // linear seek to the sample
1170         int64_t start_frame = 0;
1171 // TODO: Use bisection also
1172 //      printf("Next page granulepos: %lli, pagepos: %lli\n", end_sample, sw->file_pagepos_found);
1173         int discard_packets = 0;
1174         int missp = 0;
1175         int missm = 0;
1176         if (pageend_frame <= frame)
1177         {
1178         // scan forward
1179                 while (pageend_frame < frame)
1180                 {
1181                         do {
1182                                 ogg_get_next_page(sw, serialno, og); 
1183                         } while (ogg_page_packets(og) == 0);
1184                         pageend_frame = theora_granule_frame(&tf->td, ogg_page_granulepos(og));
1185                         missp++;
1186                 }
1187                 // go back if this frame starts on previous page
1188                 if (ogg_page_continued(og) && pageend_frame - ogg_page_packets(og) == frame - 1)
1189                 {
1190                         do {
1191                                 ogg_get_prev_page(sw, serialno, og); 
1192                         } while (ogg_page_packets(og) == 0 && ogg_page_continued(og));          
1193                 }
1194                 pageend_frame = theora_granule_frame(&tf->td, ogg_page_granulepos(og));
1195         } else
1196         {
1197         // scan backward
1198                 int64_t first_frame_on_page = theora_granule_frame(&tf->td, ogg_page_granulepos(og)) - ogg_page_packets(og) + 2;
1199                 if (!ogg_page_continued(og))
1200                         first_frame_on_page--;
1201                 while (first_frame_on_page > frame)
1202                 {
1203 //                      printf("get prev page: %lli pagepos:%lli\n", ogg_page_granulepos(og), sw->file_pagepos_found);
1204                         do {
1205                                 ogg_get_prev_page(sw, serialno, og); 
1206                         } while (ogg_page_packets(og) == 0 && ogg_page_continued(og));          
1207                         missm++;
1208 //                      pageend_frame = theora_granule_frame(&tf->td, ogg_page_granulepos(og));
1209                         first_frame_on_page = theora_granule_frame(&tf->td, ogg_page_granulepos(og)) - ogg_page_packets(og) + 2;
1210                         if (!ogg_page_continued(og))
1211                                 first_frame_on_page--;
1212                 }
1213         }
1214 //      printf("Miss plus: %i, miss minus: %i\n", missp, missm);
1215 //      printf("last frame of page with frame : %lli\n", pageend_frame);
1216         return 1;                       
1220 int FileOGG::ogg_seek_to_keyframe(sync_window_t *sw, long serialno, int64_t frame, int64_t *keyframe_number)
1222         ogg_page og;
1223         ogg_packet op;
1224 //      printf("Searching for the proper position to start decoding frame %lli\n", frame);
1225         if (!ogg_get_page_of_frame(sw, serialno, &og, frame))
1226         {
1227                 eprintf("Seeking to frame failed\n");
1228                 return 0;
1229         }
1230         // TODO: if the frame we are looking for continoues on the next page, we don't need to do this
1231         // Now go to previous page in order to find out the granulepos
1232         // Don't do it in case this is the first page.
1233 //      printf("GP: %lli\n", ogg_page_granulepos(&og));
1234         int64_t granulepos, iframe, pframe;
1235         granulepos = ogg_page_granulepos(&og);
1236         iframe = granulepos >> theora_keyframe_granule_shift;
1237         pframe = granulepos - (iframe << theora_keyframe_granule_shift);
1238         // check if maybe iframe is known from this page already
1239         if (granulepos != -1 && iframe <= frame)
1240         {
1241                 // optimisation, iframe is already known from this page
1242         } else
1243         {
1244                 // get previous page so we will get the iframe number 
1245                 do {
1246                         ogg_get_prev_page(sw, serialno, &og); 
1247                 } while (ogg_page_packets(&og) == 0);           
1249                 granulepos = ogg_page_granulepos(&og);
1250                 iframe = granulepos >> theora_keyframe_granule_shift;
1251                 pframe = granulepos - (iframe << theora_keyframe_granule_shift);
1252         }
1253         int64_t first_frame_on_page = theora_granule_frame(&tf->td, ogg_page_granulepos(&og)) - ogg_page_packets(&og) + 2;
1254         if (!ogg_page_continued(&og))
1255                 first_frame_on_page--;
1256         if (first_frame_on_page <= iframe)
1257         {
1258                 // optimisation, happens mainly in low-bitrate streams, it spares us one seek
1259         } else
1260         {
1261                 // get the page where keyframe starts
1262                 if (!ogg_get_page_of_frame(sw, serialno, &og, iframe))
1263                 {
1264                         eprintf("Seeking to frame failed\n");
1265                         return 0;
1266                 }
1267         }               
1268 //      printf("looking for frame: %lli, last frame of the page: %lli, last keyframe: %lli\n", frame, pframe+iframe, iframe);
1269         ogg_stream_reset(&tf->to);
1270         ogg_stream_pagein(&tf->to, &og);
1271         // Read until one frame before keyframe
1272 //      printf("c: %i\n", ogg_page_continued(&og));
1273         int numread = iframe - (theora_granule_frame(&tf->td, ogg_page_granulepos(&og)) - ogg_page_packets(&og)) - 1;
1274         if (ogg_page_continued(&og))
1275                 numread--;
1276 //      printf("numread: %i\n", numread);
1277 //      printf("FileOGG:: Proper position: %lli\n", theora_granule_frame(&tf->td, ogg_page_granulepos(&og)) + numread - ogg_page_packets(&og));
1278         while (numread > 0)
1279         {
1280                 while (ogg_stream_packetpeek(&tf->to, NULL) != 1)
1281                 {
1282                         if (!ogg_get_next_page(sw, serialno, &og))
1283                         {
1284                                 eprintf("Cannot find next page while seeking\n");
1285                                 return 0;
1286                         }
1287                         ogg_stream_pagein(&tf->to, &og);
1288                 }
1289                 ogg_stream_packetout(&tf->to, &op);
1290                 numread --;
1291         }
1292         *keyframe_number = iframe;
1293         return 1;
1297 int FileOGG::check_sig(Asset *asset)
1300         FILE *fd = fopen(asset->path, "rb");
1302 // Test for "OggS"
1303         fseek(fd, 0, SEEK_SET);
1304         char data[4];
1306         fread(data, 4, 1, fd);
1308         if(data[0] == 'O' &&
1309                 data[1] == 'g' &&
1310                 data[2] == 'g' &&
1311                 data[3] == 'S')
1312         {
1314                 fclose(fd);
1315 //              printf("Yay, we have an ogg file\n");
1317                 return 1;
1318         }
1320         fclose(fd);
1322         return 0;
1323         
1326 int FileOGG::close_file()
1329         if (wr)
1330         {
1331                 if (final_write)
1332                 {
1333                         if (asset->audio_data)
1334                                 write_samples_vorbis(0, 0, 1); // set eos
1335                         if (asset->video_data)
1336                                 write_frames_theora(0, 1, 1); // set eos
1337                 }
1338                 flush_ogg(1); // flush all
1339         
1340                 if (asset->audio_data)
1341                 {
1342                         vorbis_block_clear (&tf->vb);
1343                         vorbis_dsp_clear (&tf->vd);
1344                         vorbis_info_clear (&tf->vi);
1345                         ogg_stream_clear (&tf->vo);
1346                 }
1347                 if (asset->video_data)
1348                 {
1349                         theora_info_clear (&tf->ti);
1350                         ogg_stream_clear (&tf->to);
1351                         theora_clear (&tf->td);
1352                 }
1353                 
1354                 if (stream) fclose(stream);
1355                 stream = 0;
1356         } else if (rd) 
1357         {       
1358                 if (asset->audio_data)
1359                 {
1360                         vorbis_block_clear (&tf->vb);
1361                         vorbis_dsp_clear (&tf->vd);
1362                         vorbis_comment_clear (&tf->vc);
1363                         vorbis_info_clear (&tf->vi);
1364                         ogg_stream_clear (&tf->vo);
1365                 }
1366                 theora_comment_clear(&tf->tc);
1367                 if (asset->video_data)
1368                 {
1369                         theora_info_clear (&tf->ti);
1370                         theora_comment_clear (&tf->tc);
1371                         theora_clear (&tf->td);
1372                         ogg_stream_clear (&tf->to);
1373                 }
1374                 
1375                         
1376                 if (stream) fclose(stream);
1377                 stream = 0;
1379         }
1382 int FileOGG::close_file_derived()
1384 //printf("FileOGG::close_file_derived(): 1\n");
1385         if (stream) fclose(stream);
1386         stream = 0;
1389 int64_t FileOGG::get_video_position()
1391 //      printf("GVP\n");
1392         return next_frame_position - start_frame;
1395 int64_t FileOGG::get_audio_position()
1397         return next_sample_position - start_sample;
1400 int FileOGG::set_video_position(int64_t x)
1402 //      x=0;
1403 //      printf("SVP: %lli\n", x);
1404         
1405         next_frame_position = x + start_frame;
1406         return 1;
1410 int FileOGG::colormodel_supported(int colormodel)
1412 //      printf("CMS\n");
1414         if (colormodel == BC_YUV420P)
1415                 return BC_YUV420P;
1416         else
1417                 return colormodel;
1419 int FileOGG::get_best_colormodel(Asset *asset, int driver)
1422         return BC_YUV420P;
1426 int FileOGG::read_frame(VFrame *frame)
1429         if(!stream) return 1;
1431         
1432         // skip is cheaper than seek, do it...
1433         int decode_frames = 0;
1434         int expect_keyframe = 0;
1435         if (ogg_frame_position >= 0 && 
1436             next_frame_position >= ogg_frame_position && 
1437             next_frame_position - ogg_frame_position < 32)
1438         {
1439                 decode_frames = next_frame_position - ogg_frame_position;
1440         } else
1441         if (next_frame_position != ogg_frame_position)
1442         {
1443                 if (!ogg_seek_to_keyframe(tf->videosync, tf->to.serialno, next_frame_position, &ogg_frame_position))
1444                 {
1445                         eprintf("Error while seeking to frame's keyframe (frame: %lli, keyframe: %lli)\n", next_frame_position, ogg_frame_position);
1446                         return 1;
1447                 }
1448 //              printf("For frame: %lli, keyframe is: %lli\n", next_frame_position,ogg_frame_position);
1449                 // skip frames must be > 0 here
1450                 decode_frames = next_frame_position - ogg_frame_position + 1; 
1451                 ogg_frame_position --; // ogg_frame_position is at last decoded frame, so it will point right 
1452                 if (decode_frames <= 0) 
1453                 {
1454                         eprintf("Error while seeking to keyframe, wrong keyframe number (frame: %lli, keyframe: %lli)\n", next_frame_position, ogg_frame_position);
1455                         return 1;
1456                         
1457                 }
1458                 expect_keyframe = 1;
1459         }
1461 //      printf("Frames to decode: %i\n", decode_frames);
1463 // THIS IS WHAT CAUSES SLOWNESS OF SEEKING, but we can do nothing about it.
1464         while (decode_frames > 0)
1465         {
1466                 ogg_page og;
1467                 ogg_packet op;
1468                 while (ogg_stream_packetpeek(&tf->to, NULL) != 1)
1469                 {
1470                         if (!ogg_get_next_page(tf->videosync, tf->to.serialno, &og))
1471                         {
1472                                 eprintf("Cannot find next page while seeking\n");
1473                                 return 1;
1474                         }
1475                         ogg_stream_pagein(&tf->to, &og);
1476                 }
1477                 ogg_stream_packetout(&tf->to, &op);
1478                 if (expect_keyframe && !theora_packet_iskeyframe(&op))
1479                 {
1480                                 eprintf("Expecting a keyframe, but didn't get it\n");
1481                         //      return 1; this is generally not a fatal error
1482                 }
1483                 expect_keyframe = 0;
1484                 
1485                 // decode
1486                 theora_decode_packetin(&tf->td, &op);
1488                 decode_frames --;
1489                 ogg_frame_position ++;
1490         }
1491         {
1492                 yuv_buffer yuv;
1493                 int ret = theora_decode_YUVout (&tf->td, &yuv);
1494                 if (ret)
1495                 {
1496                         eprintf("theora_decode_YUVout() failed with code %i\n", ret);
1497                 }
1499 // Dirty magic 
1500 /*              yuv.y += yuv.y_stride * (yuv.y_height - 1);
1501                 yuv.u += yuv.uv_stride * (yuv.uv_height - 1);
1502                 yuv.v += yuv.uv_stride * (yuv.uv_height - 1);
1503                 yuv.y_stride = - yuv.y_stride;
1504                 yuv.uv_stride = - yuv.uv_stride;*/
1505                 VFrame *temp_frame = new VFrame(yuv.y, 
1506                                                 0,
1507                                                 yuv.u - yuv.y,
1508                                                 yuv.v - yuv.y,
1509                                                 - yuv.y_stride,
1510                                                 yuv.y_height,
1511                                                 BC_YUV420P,
1512                                                 - yuv.y_stride);
1513                 // copy into temp frame...
1514                 
1515                 cmodel_transfer(frame->get_rows(),
1516                         temp_frame->get_rows(),
1517                         frame->get_y(),
1518                         frame->get_u(),
1519                         frame->get_v(),
1520                         temp_frame->get_y(),
1521                         temp_frame->get_u(),
1522                         temp_frame->get_v(),
1523                         0,
1524                         0,
1525                         yuv.y_width,
1526                         yuv.y_height,
1527                         0,
1528                         0,
1529                         yuv.y_width,  // temp_frame can be larger than frame if width not dividable by 16
1530                         yuv.y_height,   
1531                         BC_YUV420P,
1532                         frame->get_color_model(),
1533                         0,
1534                         -temp_frame->get_w(),
1535                         frame->get_w());
1536                 delete temp_frame;
1537         }
1539         next_frame_position ++;
1540         
1541         return 0;               
1546 int FileOGG::ogg_decode_more_samples(sync_window_t *sw, long serialno)
1548         ogg_page og;
1549         ogg_packet op;
1550         int done = 0;
1551         while (!done)
1552         {
1553                 while (ogg_stream_packetpeek(&tf->vo, NULL) != 1)
1554                 {
1555                         if (!ogg_get_next_page(sw, serialno, &og))
1556                         {
1557                                 eprintf("Cannot find next page while trying to decode more samples\n");
1558                                 return 0;
1559                         }
1560                         ogg_stream_pagein(&tf->vo, &og);
1561                 }
1562                 ogg_stream_packetout(&tf->vo, &op);
1563                 if(!vorbis_synthesis(&tf->vb, &op))
1564                 {
1565                         done = 1;       
1566                         vorbis_synthesis_blockin(&tf->vd, &tf->vb);
1567                 }
1568         }
1569         return 1;
1572 int FileOGG::set_audio_position(int64_t x)
1574         next_sample_position = x + start_sample;
1575         return 0;
1578 int FileOGG::move_history(int from, int to, int len)
1580         for(int i = 0; i < asset->channels; i++)
1581                 memmove(pcm_history[i] + to, pcm_history[i] + from, sizeof(float) * len);
1582         history_start = history_start + from - to;
1583         return 0;
1586 int FileOGG::read_samples(double *buffer, int64_t len)
1588         float **vorbis_buffer;
1589         if (len <= 0) 
1590                 return 0;
1591 //      printf("Reading samples: Channel: %i, number of samples: %lli, reading at :%lli\n", file->current_channel, len, next_sample_position);
1592 //              printf("\tnext_sample_position: %lli, length: %i\n", next_sample_position, len);
1593 //              printf("\thistory_start: %lli, length: %i\n", history_start, history_size);
1595         if(len > HISTORY_MAX)
1596         {
1597                 eprintf("max samples=%d\n", HISTORY_MAX);
1598                 return 1;
1599         }
1601         if(!pcm_history)
1602         {
1603                 pcm_history = new float*[asset->channels];
1604                 for(int i = 0; i < asset->channels; i++)
1605                         pcm_history[i] = new float[HISTORY_MAX];
1606                 history_start = -100000000; // insane value to trigger reload
1607                 history_size = 0;
1608         }
1610         int64_t hole_start = -1;
1611         int64_t hole_len = -1;
1612         int64_t hole_absstart = -1;
1613         int64_t hole_fill = 0;
1615         if (history_start < next_sample_position && history_start + history_size > next_sample_position && history_start + history_size < next_sample_position + len) 
1616         {
1617 //              printf("a\n");
1618                 hole_fill = 1;
1619                 hole_start = history_start + history_size - next_sample_position;
1620                 hole_len = history_size - hole_start;
1621                 hole_absstart = next_sample_position + hole_start;
1622                 move_history(next_sample_position - history_start,
1623                                 0,
1624                                 hole_start); // 
1625                 
1626         } else
1627         if (next_sample_position < history_start && history_start < next_sample_position + len)
1628         {
1629 //              printf("b\n");
1630                 hole_fill = 1;
1631                 hole_start = 0;
1632                 hole_len = history_start - next_sample_position;
1633                 hole_absstart = next_sample_position;
1634 //              printf("hs: %lli, histstart: %lli, next_sample_position: %lli\n", history_size, history_start, next_sample_position);
1635 //              printf("to: 0, from: %lli, size: %lli\n", 
1636  //                             history_start - next_sample_position,
1637 //                              history_size - history_start + next_sample_position);
1638                 move_history(0, 
1639                                 history_start - next_sample_position,
1640                                 history_size - history_start + next_sample_position);
1641                         
1642         } else 
1643         if (next_sample_position >= history_start + history_size || next_sample_position + len <= history_start)
1644         {
1645 //              printf("c\n");
1646                 hole_fill = 1;
1647                 hole_start = 0;
1648                 hole_len = HISTORY_MAX;
1649                 hole_absstart = next_sample_position;
1650                 history_start = hole_absstart;
1651                 history_size = hole_len;
1652         }
1653         
1654         if (hole_fill)
1655         {
1656                 if (hole_start < 0 || hole_len <= 0 || hole_absstart < 0)
1657                 {
1658                         eprintf("Error at finding out which range to read from file\n");
1659                         return 1;
1660                 }
1661                 
1662                 if (hole_absstart + hole_len > asset->audio_length + start_sample)
1663                 {
1664                         hole_len = asset->audio_length + start_sample - hole_absstart;
1665                         history_size = asset->audio_length + start_sample - history_start;
1666                 } else
1667                 {
1668                         history_size = HISTORY_MAX;
1669                 }
1670                 
1671                 
1672 //              printf("Decode samples at position: %lli, samples to read: %lli\n", hole_absstart, hole_len);
1673         
1674                 int64_t samples_read = 0;        
1675                 if (ogg_sample_position != hole_absstart)
1676                 {
1677                         ogg_sample_position = hole_absstart;
1678                         if (!ogg_seek_to_sample(tf->audiosync, tf->vo.serialno, ogg_sample_position))
1679                         {
1680                                 eprintf("Error while seeking to sample\n");
1681                                 return 1;
1682                         }
1683                 }
1684                 // now we have ogg_sample_positon aligned
1685                 int64_t samples_to_read = hole_len;
1686                 while (samples_read < hole_len)
1687                 {
1688                         int64_t waiting_samples = vorbis_synthesis_pcmout(&tf->vd, &vorbis_buffer);
1689                         int64_t takeout_samples;
1690                         if (waiting_samples > samples_to_read - samples_read)
1691                                 takeout_samples = samples_to_read - samples_read;
1692                         else 
1693                                 takeout_samples = waiting_samples;
1695                         int i, j;
1696 //                      printf("takeout samples: %lli, samples_read: %lli\n", takeout_samples, samples_read);
1697                         for(int i = 0; i < asset->channels; i++)
1698                         {
1699                                 float *input = vorbis_buffer[i];
1700                                 float *output = pcm_history[i] + hole_start;
1701                                 // TODO: use memcpy
1702                                 for(int j = 0; j < takeout_samples ; j++)
1703                                 {
1704                                         output[j] = input[j];
1705                                 }
1706                         }                                                                   
1707                         
1708                         vorbis_synthesis_read(&tf->vd, takeout_samples);
1709                         samples_read += takeout_samples;
1710                         ogg_sample_position += takeout_samples;
1711                         hole_start += takeout_samples;
1712                         
1713                         if (samples_read < hole_len)
1714                                 if (!ogg_decode_more_samples(tf->audiosync, tf->vo.serialno))
1715                                 {
1716                                         ogg_sample_position = -1;
1717                                         return 1;
1718                                 }
1721                 }
1722         }       
1723         
1724         // now we can be sure our history is correct, just copy it out
1725         if (next_sample_position < history_start || next_sample_position + len > history_start + history_size)
1726         {
1727                 eprintf("History not aligned properly \n\tnext_sample_position: %lli, length: %i\n\thistory_start: %lli, length: %i\n", next_sample_position, len, history_start, history_size);
1728                 return 1;
1729         }
1730         float *input = pcm_history[file->current_channel] + next_sample_position - history_start;
1731         for (int i = 0; i < len; i++)
1732                 buffer[i] = input[i];
1733          
1734         next_sample_position += len;
1735         return 0;
1739 int FileOGG::write_audio_page()
1741         int ret;
1743         ret = fwrite(tf->apage, 1, tf->apage_len, stream);
1744         if(ret < tf->apage_len) 
1745         {
1746                 eprintf("error writing audio page\n");
1747         }
1748         tf->apage_valid = 0;
1749         tf->a_pkg -= ogg_page_packets((ogg_page *)&tf->apage);
1750         return ret;
1753 int FileOGG::write_video_page()
1755         int ret;
1757         ret = fwrite(tf->vpage, 1, tf->vpage_len, stream);
1758         if(ret < tf->vpage_len) 
1759         {
1760                 eprintf("error writing video page\n");
1761         }
1762         tf->vpage_valid = 0;
1763         tf->v_pkg -= ogg_page_packets((ogg_page *)&tf->vpage);
1764         return ret;
1767 void FileOGG::flush_ogg (int e_o_s)
1769     int len;
1770     ogg_page og;
1772         flush_lock->lock();
1773     /* flush out the ogg pages  */
1774     while(1) {
1775       /* Get pages for both streams, if not already present, and if available.*/
1776       if(asset->video_data && !tf->vpage_valid) {
1777         // this way seeking is much better,
1778         // not sure if 23 packets  is a good value. it works though
1779         int v_next=0;
1780         if(tf->v_pkg>22 && ogg_stream_flush(&tf->to, &og) > 0) {
1781           v_next=1;
1782         }
1783         else if(ogg_stream_pageout(&tf->to, &og) > 0) {
1784           v_next=1;
1785         }
1786         if(v_next) {
1787           len = og.header_len + og.body_len;
1788           if(tf->vpage_buffer_length < len) {
1789             tf->vpage = (unsigned char *)realloc(tf->vpage, len);
1790             tf->vpage_buffer_length = len;
1791           }
1792           tf->vpage_len = len;
1793           memcpy(tf->vpage, og.header, og.header_len);
1794           memcpy(tf->vpage+og.header_len , og.body, og.body_len);
1796           tf->vpage_valid = 1;
1797           tf->videotime = theora_granule_time (&tf->td,
1798                   ogg_page_granulepos(&og));
1799         }
1800       }
1801       if(asset->audio_data && !tf->apage_valid) {
1802         // this way seeking is much better,
1803         // not sure if 23 packets  is a good value. it works though
1804         int a_next=0;
1805         if(tf->a_pkg>22 && ogg_stream_flush(&tf->vo, &og) > 0) {
1806           a_next=1;
1807         }
1808         else if(ogg_stream_pageout(&tf->vo, &og) > 0) {
1809           a_next=1;
1810         }
1811         if(a_next) {
1812           len = og.header_len + og.body_len;
1813           if(tf->apage_buffer_length < len) {
1814             tf->apage = (unsigned char *)realloc(tf->apage, len);
1815             tf->apage_buffer_length = len;
1816           }
1817           tf->apage_len = len;
1818           memcpy(tf->apage, og.header, og.header_len);
1819           memcpy(tf->apage+og.header_len , og.body, og.body_len);
1821           tf->apage_valid = 1;
1822           tf->audiotime= vorbis_granule_time (&tf->vd, 
1823                   ogg_page_granulepos(&og));
1824         }
1825       }
1827       if(!asset->audio_data && tf->vpage_valid) {
1828         write_video_page();
1829       }
1830       else if(!asset->video_data && tf->apage_valid) {
1831         write_audio_page();
1832       }
1833       /* We're using both. We can output only:
1834        *  a) If we have valid pages for both
1835        *  b) At EOS, for the remaining stream.
1836        */
1837       else if(tf->vpage_valid && tf->apage_valid) {
1838         /* Make sure they're in the right order. */
1839         if(tf->videotime <= tf->audiotime)
1840           write_video_page();
1841         else
1842           write_audio_page();
1843       } 
1844       else if(e_o_s && tf->vpage_valid) {
1845           write_video_page();
1846       }
1847       else if(e_o_s && tf->apage_valid) {
1848           write_audio_page();
1849       }
1850       else {
1851         break; /* Nothing more writable at the moment */
1852       }
1853     }
1854         flush_lock->unlock();
1858 int FileOGG::write_samples_vorbis(double **buffer, int64_t len, int e_o_s)
1860         int i,j, count = 0;
1861         float **vorbis_buffer;
1862         static int samples = 0;
1863         samples += len;
1864         if(e_o_s)
1865         {
1866                 vorbis_analysis_wrote (&tf->vd, 0);
1867         } else
1868         {
1869                 vorbis_buffer = vorbis_analysis_buffer (&tf->vd, len);
1870                 /* double to float conversion */
1871                 for(i = 0; i<asset->channels; i++)
1872                 {
1873                         for (j = 0; j < len; j++)
1874                         {
1875                                 vorbis_buffer[i][j] = buffer[i][j];
1876                         }
1877                 }
1878                 vorbis_analysis_wrote (&tf->vd, len);
1879         }
1880         while(vorbis_analysis_blockout (&tf->vd, &tf->vb) == 1)
1881         {
1882             /* analysis, assume we want to use bitrate management */
1883             vorbis_analysis (&tf->vb, NULL);
1884             vorbis_bitrate_addblock (&tf->vb);
1885             
1886             /* weld packets into the bitstream */
1887             while (vorbis_bitrate_flushpacket (&tf->vd, &tf->op))
1888             {
1889                 flush_lock->lock();
1890                 ogg_stream_packetin (&tf->vo, &tf->op);
1891                 tf->a_pkg++;
1892                 flush_lock->unlock();
1893             }
1895         }
1896         flush_ogg(0);
1897         return 0;
1902 int FileOGG::write_samples(double **buffer, int64_t len)
1904         if (len > 0)
1905                 return write_samples_vorbis(buffer, len, 0);
1906         return 0;
1909 int FileOGG::write_frames_theora(VFrame ***frames, int len, int e_o_s)
1911         // due to clumsy theora's design we need to delay writing out by one frame
1912         // always stay one frame behind, so we can correctly encode e_o_s
1914         int i, j, result = 0;
1916         if(!stream) return 0;
1918         
1919         for(j = 0; j < len && !result; j++)
1920         {
1921                 if (temp_frame) // encode previous frame if available
1922                 {
1923                         yuv_buffer yuv;
1924                         yuv.y_width = tf->ti.width;
1925                         yuv.y_height = tf->ti.height;
1926                         yuv.y_stride = temp_frame->get_bytes_per_line();
1928                         yuv.uv_width = tf->ti.width / 2;
1929                         yuv.uv_height = tf->ti.height / 2;
1930                         yuv.uv_stride = temp_frame->get_bytes_per_line() /2;
1932                         yuv.y = temp_frame->get_y();
1933                         yuv.u = temp_frame->get_u();
1934                         yuv.v = temp_frame->get_v();
1935                         int ret = theora_encode_YUVin (&tf->td, &yuv);
1936                         if (ret)
1937                         {
1938                                 eprintf("theora_encode_YUVin() failed with code %i\nyuv_buffer: y_width: %i, y_height: %i, y_stride: %i, uv_width: %i, uv_height: %i, uv_stride: %i\n", 
1939                                         ret,
1940                                         yuv.y_width,
1941                                         yuv.y_height,
1942                                         yuv.y_stride,
1943                                         yuv.uv_width,
1944                                         yuv.uv_height,
1945                                         yuv.uv_stride);
1946                         }
1947                         
1948                         while(theora_encode_packetout (&tf->td, e_o_s, &tf->op)) {
1949                                 flush_lock->lock();
1950                                 ogg_stream_packetin (&tf->to, &tf->op);
1951                                 tf->v_pkg++;
1952                                 flush_lock->unlock();
1953             }
1954                         flush_ogg(0);  // eos flush is done later at close_file
1955                 }
1956 // If we have e_o_s, don't encode any new frames
1957                 if (e_o_s) 
1958                         break;
1960                 if (!temp_frame)
1961                 {
1962                         temp_frame = new VFrame (0, 
1963                                                 tf->ti.width, 
1964                                                 tf->ti.height,
1965                                                 BC_YUV420P);
1966                 } 
1967                 VFrame *frame = frames[0][j];
1968                 int in_color_model = frame->get_color_model();
1969                 if (in_color_model == BC_YUV422P &&
1970                     temp_frame->get_w() == frame->get_w() &&
1971                     temp_frame->get_h() == frame->get_h() &&
1972                     temp_frame->get_bytes_per_line() == frame->get_bytes_per_line())
1973                 {
1974                         temp_frame->copy_from(frame);
1975                 } else
1976                 {
1978                         cmodel_transfer(temp_frame->get_rows(),
1979                                 frame->get_rows(),
1980                                 temp_frame->get_y(),
1981                                 temp_frame->get_u(),
1982                                 temp_frame->get_v(),
1983                                 frame->get_y(),
1984                                 frame->get_u(),
1985                                 frame->get_v(),
1986                                 0,
1987                                 0,
1988                                 frame->get_w(),
1989                                 frame->get_h(),
1990                                 0,
1991                                 0,
1992                                 frame->get_w(),  // temp_frame can be larger than frame if width not dividable by 16
1993                                 frame->get_h(), 
1994                                 frame->get_color_model(),
1995                                 BC_YUV420P,
1996                                 0,
1997                                 frame->get_w(),
1998                                 temp_frame->get_w());
2000                 }
2001         }                                               
2002                                 
2003         return 0;
2007 int FileOGG::write_frames(VFrame ***frames, int len)
2009         
2010         return write_frames_theora(frames, len, 0);
2013 OGGConfigAudio::OGGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
2014  : BC_Window(PROGRAM_NAME ": Audio Compression",
2015         parent_window->get_abs_cursor_x(1),
2016         parent_window->get_abs_cursor_y(1),
2017         350,
2018         250)
2020         this->parent_window = parent_window;
2021         this->asset = asset;
2024 OGGConfigAudio::~OGGConfigAudio()
2029 int OGGConfigAudio::create_objects()
2031 //      add_tool(new BC_Title(10, 10, _("There are no audio options for this format")));
2033         int x = 10, y = 10;
2034         int x1 = 150;
2035         char string[BCTEXTLEN];
2037         add_tool(fixed_bitrate = new OGGVorbisFixedBitrate(x, y, this));
2038         add_tool(variable_bitrate = new OGGVorbisVariableBitrate(x1, y, this));
2040         y += 30;
2041         sprintf(string, "%d", asset->vorbis_min_bitrate);
2042         add_tool(new BC_Title(x, y, _("Min bitrate:")));
2043         add_tool(new OGGVorbisMinBitrate(x1, y, this, string));
2045         y += 30;
2046         add_tool(new BC_Title(x, y, _("Avg bitrate:")));
2047         sprintf(string, "%d", asset->vorbis_bitrate);
2048         add_tool(new OGGVorbisAvgBitrate(x1, y, this, string));
2050         y += 30;
2051         add_tool(new BC_Title(x, y, _("Max bitrate:")));
2052         sprintf(string, "%d", asset->vorbis_max_bitrate);
2053         add_tool(new OGGVorbisMaxBitrate(x1, y, this, string));
2056         add_subwindow(new BC_OKButton(this));
2057         show_window();
2058         flush();
2059         return 0;
2065 int OGGConfigAudio::close_event()
2067         set_done(0);
2068         return 1;
2071 OGGVorbisFixedBitrate::OGGVorbisFixedBitrate(int x, int y, OGGConfigAudio *gui)
2072  : BC_Radial(x, y, !gui->asset->vorbis_vbr, _("Average bitrate"))
2074         this->gui = gui;
2076 int OGGVorbisFixedBitrate::handle_event()
2078         gui->asset->vorbis_vbr = 0;
2079         gui->variable_bitrate->update(0);
2080         return 1;
2083 OGGVorbisVariableBitrate::OGGVorbisVariableBitrate(int x, int y, OGGConfigAudio *gui)
2084  : BC_Radial(x, y, gui->asset->vorbis_vbr, _("Variable bitrate"))
2086         this->gui = gui;
2088 int OGGVorbisVariableBitrate::handle_event()
2090         gui->asset->vorbis_vbr = 1;
2091         gui->fixed_bitrate->update(0);
2092         return 1;
2096 OGGVorbisMinBitrate::OGGVorbisMinBitrate(int x, 
2097         int y, 
2098         OGGConfigAudio *gui, 
2099         char *text)
2100  : BC_TextBox(x, y, 180, 1, text)
2102         this->gui = gui;
2104 int OGGVorbisMinBitrate::handle_event()
2106         gui->asset->vorbis_min_bitrate = atol(get_text());
2107         return 1;
2112 OGGVorbisMaxBitrate::OGGVorbisMaxBitrate(int x, 
2113         int y, 
2114         OGGConfigAudio *gui,
2115         char *text)
2116  : BC_TextBox(x, y, 180, 1, text)
2118         this->gui = gui;
2120 int OGGVorbisMaxBitrate::handle_event()
2122         gui->asset->vorbis_max_bitrate = atol(get_text());
2123         return 1;
2128 OGGVorbisAvgBitrate::OGGVorbisAvgBitrate(int x, int y, OGGConfigAudio *gui, char *text)
2129  : BC_TextBox(x, y, 180, 1, text)
2131         this->gui = gui;
2133 int OGGVorbisAvgBitrate::handle_event()
2135         gui->asset->vorbis_bitrate = atol(get_text());
2136         return 1;
2143 OGGConfigVideo::OGGConfigVideo(BC_WindowBase *parent_window, Asset *asset)
2144  : BC_Window(PROGRAM_NAME ": Video Compression",
2145         parent_window->get_abs_cursor_x(1),
2146         parent_window->get_abs_cursor_y(1),
2147         450,
2148         220)
2150         this->parent_window = parent_window;
2151         this->asset = asset;
2154 OGGConfigVideo::~OGGConfigVideo()
2159 int OGGConfigVideo::create_objects()
2161 //      add_tool(new BC_Title(10, 10, _("There are no video options for this format")));
2162         int x = 10, y = 10;
2163         int x1 = x + 150;
2164         int x2 = x + 300;
2166         add_subwindow(new BC_Title(x, y + 5, _("Bitrate:")));
2167         add_subwindow(new OGGTheoraBitrate(x1, y, this));
2168         add_subwindow(fixed_bitrate = new OGGTheoraFixedBitrate(x2, y, this));
2169         y += 30;
2171         add_subwindow(new BC_Title(x, y, _("Quality:")));
2172         add_subwindow(new BC_ISlider(x + 80, 
2173                 y,
2174                 0,
2175                 200,
2176                 200,
2177                 0,
2178                 63,
2179                 asset->theora_quality,
2180                 0,
2181                 0,
2182                 &asset->theora_quality));
2184         
2185         add_subwindow(fixed_quality = new OGGTheoraFixedQuality(x2, y, this));
2186         y += 30;
2188         add_subwindow(new BC_Title(x, y, _("Keyframe frequency:")));
2189         OGGTheoraKeyframeFrequency *keyframe_frequency = 
2190                 new OGGTheoraKeyframeFrequency(x1 + 60, y, this);
2191         keyframe_frequency->create_objects();
2192         y += 30;
2193         
2194         add_subwindow(new BC_Title(x, y, _("Keyframe force frequency:")));
2195         OGGTheoraKeyframeForceFrequency *keyframe_force_frequency = 
2196                 new OGGTheoraKeyframeForceFrequency(x1 + 60, y, this);
2197         keyframe_force_frequency->create_objects();
2198         y += 30;
2200         add_subwindow(new BC_Title(x, y, _("Sharpness:")));
2201         OGGTheoraSharpness *sharpness = 
2202                 new OGGTheoraSharpness(x1 + 60, y, this);
2203         sharpness->create_objects();
2204         y += 30;
2205         
2207         add_subwindow(new BC_OKButton(this));
2208         return 0;
2214 int OGGConfigVideo::close_event()
2216         set_done(0);
2217         return 1;
2220 OGGTheoraBitrate::OGGTheoraBitrate(int x, int y, OGGConfigVideo *gui)
2221  : BC_TextBox(x, y, 100, 1, gui->asset->theora_bitrate)
2223         this->gui = gui;
2227 int OGGTheoraBitrate::handle_event()
2229         // TODO: MIN / MAX check
2230         gui->asset->theora_bitrate = atol(get_text());
2231         return 1;
2237 OGGTheoraFixedBitrate::OGGTheoraFixedBitrate(int x, int y, OGGConfigVideo *gui)
2238  : BC_Radial(x, y, gui->asset->theora_fix_bitrate, _("Fixed bitrate"))
2240         this->gui = gui;
2243 int OGGTheoraFixedBitrate::handle_event()
2245         update(1);
2246         gui->asset->theora_fix_bitrate = 1;
2247         gui->fixed_quality->update(0);
2248         return 1;
2251 OGGTheoraFixedQuality::OGGTheoraFixedQuality(int x, int y, OGGConfigVideo *gui)
2252  : BC_Radial(x, y, !gui->asset->theora_fix_bitrate, _("Fixed quality"))
2254         this->gui = gui;
2257 int OGGTheoraFixedQuality::handle_event()
2259         update(1);
2260         gui->asset->theora_fix_bitrate = 0;
2261         gui->fixed_bitrate->update(0);
2262         return 1;
2265 OGGTheoraKeyframeFrequency::OGGTheoraKeyframeFrequency(int x, int y, OGGConfigVideo *gui)
2266  : BC_TumbleTextBox(gui, 
2267         (int64_t)gui->asset->theora_keyframe_frequency, 
2268         (int64_t)1,
2269         (int64_t)500,
2270         x, 
2271         y,
2272         40)
2274         this->gui = gui;
2277 int OGGTheoraKeyframeFrequency::handle_event()
2279         gui->asset->theora_keyframe_frequency = atol(get_text());
2280         return 1;
2283 OGGTheoraKeyframeForceFrequency::OGGTheoraKeyframeForceFrequency(int x, int y, OGGConfigVideo *gui)
2284  : BC_TumbleTextBox(gui, 
2285         (int64_t)gui->asset->theora_keyframe_frequency, 
2286         (int64_t)1,
2287         (int64_t)500,
2288         x, 
2289         y,
2290         40)
2292         this->gui = gui;
2295 int OGGTheoraKeyframeForceFrequency::handle_event()
2297         gui->asset->theora_keyframe_frequency = atol(get_text());
2298         return 1;
2302 OGGTheoraSharpness::OGGTheoraSharpness(int x, int y, OGGConfigVideo *gui)
2303  : BC_TumbleTextBox(gui, 
2304         (int64_t)gui->asset->theora_sharpness, 
2305         (int64_t)0,
2306         (int64_t)2,
2307         x, 
2308         y,
2309         40)
2311         this->gui = gui;
2314 int OGGTheoraSharpness::handle_event()
2316         gui->asset->theora_sharpness = atol(get_text());
2317         return 1;
2321 PackagingEngineOGG::PackagingEngineOGG()
2323         packages = 0;
2324         default_asset = 0;
2327 PackagingEngineOGG::~PackagingEngineOGG()
2329         if(packages)
2330         {
2331                 for(int i = 0; i < total_packages; i++)
2332                         delete packages[i];
2333                 delete [] packages;
2334         }
2335         if (default_asset)
2336                 delete default_asset;
2341 int PackagingEngineOGG::create_packages_single_farm(
2342                 EDL *edl,
2343                 Preferences *preferences,
2344                 Asset *default_asset, 
2345                 double total_start, 
2346                 double total_end)
2348         this->total_start = total_start;
2349         this->total_end = total_end;
2350         this->edl = edl;
2352         this->preferences = preferences;
2354 // We make A COPY of the asset, because we set audio_data = 0 on local asset which is the same copy as default_asset... 
2355 // Should be taken care of somewhere else actually
2356         this->default_asset = new Asset(*default_asset);
2358         audio_start = Units::to_int64(total_start * default_asset->sample_rate);
2359         video_start = Units::to_int64(total_start * default_asset->frame_rate);
2360         audio_position = audio_start;
2361         video_position = video_start;
2362         audio_end = Units::to_int64(total_end * default_asset->sample_rate);
2363         video_end = Units::to_int64(total_end * default_asset->frame_rate);
2364         current_package = 0;
2366         double total_len = total_end - total_start;
2367 //printf("PackageDispatcher::create_packages: %f / %d = %f\n", total_len, total_packages, package_len);
2369         total_packages = 0;
2370         if (default_asset->audio_data)
2371                 total_packages++;
2372         if (default_asset->video_data)
2373                 total_packages += preferences->renderfarm_job_count;
2375         packages = new RenderPackage*[total_packages];
2377         int local_current_package = 0;
2378         if (default_asset->audio_data)
2379         {
2380                 packages[local_current_package] = new RenderPackage;
2381                 sprintf(packages[current_package]->path, "%s.audio", default_asset->path);
2382                 local_current_package++;
2383         }
2384         
2385         if (default_asset->video_data)
2386         {
2387                 video_package_len = (total_len) / preferences->renderfarm_job_count;
2388                 int current_number;    // The number being injected into the filename.
2389                 int number_start;      // Character in the filename path at which the number begins
2390                 int total_digits;      // Total number of digits including padding the user specified.
2392                 Render::get_starting_number(default_asset->path, 
2393                         current_number,
2394                         number_start, 
2395                         total_digits,
2396                         3);
2398                 for(int i = 0; i < preferences->renderfarm_job_count; i++)
2399                 {
2400                         RenderPackage *package = packages[local_current_package] = new RenderPackage;
2401                         Render::create_filename(package->path, 
2402                                 default_asset->path, 
2403                                 current_number,
2404                                 total_digits,
2405                                 number_start);
2406                         current_number++;
2407                         local_current_package++;
2408                 }
2409         }
2412 RenderPackage* PackagingEngineOGG::get_package_single_farm(double frames_per_second, 
2413                 int client_number,
2414                 int use_local_rate)
2417 //printf("PackageDispatcher::get_package %ld %ld %ld %ld\n", audio_position, video_position, audio_end, video_end);
2418         if (current_package == total_packages)
2419                 return 0;
2421         RenderPackage *result = 0;
2422         if (current_package == 0 && default_asset->audio_data)
2423         {
2424                 result = packages[0];
2425                 result->audio_start = audio_start;
2426                 result->video_start = video_start;
2427                 result->audio_end = audio_end;
2428                 result->video_end = video_end;
2429                 result->audio_do = 1;
2430                 result->video_do = 0;
2431         } else if (default_asset->video_data)
2432         {
2433                 // Do not do any scaling according to node speed, so we know we can get evenly distributed 'forced' keyframes
2434                 result = packages[current_package];
2435                 result->audio_do = 0;
2436                 result->video_do = 1;
2438                 result->audio_start = audio_position;
2439                 result->video_start = video_position;
2440                 result->audio_end = audio_position + 
2441                         Units::round(video_package_len * default_asset->sample_rate);
2442                 result->video_end = video_position + 
2443                         Units::round(video_package_len * default_asset->frame_rate);
2445 // Last package... take it all!
2446                 if (current_package == total_packages -1 ) 
2447                 {
2448                         result->audio_end = audio_end;
2449                         result->video_end = video_end;
2450                 }
2452                 audio_position = result->audio_end;
2453                 video_position = result->video_end;
2455         }
2456         
2457         current_package ++;
2458         return result;
2462 void PackagingEngineOGG::get_package_paths(ArrayList<char*> *path_list)
2464         for(int i = 0; i < total_packages; i++)
2465         {
2466                 path_list->append(strdup(packages[i]->path));
2467         }
2468 // We will mux to the the final file at the end!
2469         path_list->append(strdup(default_asset->path));
2470         path_list->set_free();
2473 int64_t PackagingEngineOGG::get_progress_max()
2475         return Units::to_int64(default_asset->sample_rate * 
2476                         (total_end - total_start)) * 2+
2477                 Units::to_int64(preferences->render_preroll * 
2478                         total_packages *
2479                         default_asset->sample_rate);
2482 int PackagingEngineOGG::packages_are_done()
2486 // Mux audio and video into one file    
2488 // First fix our asset... have to workaround the bug of corruption of local asset
2489 //      Render::check_asset(edl, *default_asset);
2491         Asset *video_asset, *audio_asset;
2492         File *audio_file_gen, *video_file_gen;
2493         FileOGG *video_file, *audio_file;
2494         ogg_stream_state audio_in_stream, video_in_stream;
2495         
2496         int local_current_package = 0;
2497         if (default_asset->audio_data)
2498         {
2499                 audio_asset = new Asset(packages[local_current_package]->path);
2500                 local_current_package++;
2502                 audio_file_gen = new File();
2503                 audio_file_gen->open_file(preferences, 
2504                         audio_asset, 
2505                         1, //rd 
2506                         0, //wr
2507                         0, //base sample rate
2508                         0); // base_frame rate
2509                 audio_file = (FileOGG*) audio_file_gen->file;
2510                 ogg_stream_init(&audio_in_stream, audio_file->tf->vo.serialno);
2511                 audio_file->ogg_seek_to_databegin(audio_file->tf->audiosync, audio_file->tf->vo.serialno);
2512         }
2514         if (default_asset->video_data)
2515         {
2516                 video_asset = new Asset(packages[local_current_package]->path);
2517                 local_current_package++;
2519                 video_file_gen = new File();
2520                 video_file_gen->open_file(preferences, 
2521                         video_asset, 
2522                         1, //rd 
2523                         0, //wr
2524                         0, //base sample rate
2525                         0); // base_frame rate
2526                 video_file = (FileOGG*) video_file_gen->file;
2527                 ogg_stream_init(&video_in_stream, video_file->tf->to.serialno);
2528                 video_file->ogg_seek_to_databegin(video_file->tf->videosync, video_file->tf->to.serialno);
2529         }
2531 // Output file
2532         File *output_file_gen = new File();
2533         output_file_gen->open_file(preferences,
2534                 default_asset,
2535                 0,
2536                 1,
2537                 default_asset->sample_rate, 
2538                 default_asset->frame_rate);
2539         FileOGG *output_file = (FileOGG*) output_file_gen->file;
2541         ogg_page og;    /* one Ogg bitstream page.  Vorbis packets are inside */
2542         ogg_packet op;  /* one raw packet of data for decode */
2545         int audio_ready = default_asset->audio_data;
2546         int video_ready = default_asset->video_data;
2547         int64_t video_packetno = 1;
2548         int64_t audio_packetno = 1;
2549         int64_t frame_offset = 0;
2550         int64_t current_frame = 0;
2551         while ((default_asset->audio_data && audio_ready) || (default_asset->video_data && video_ready))
2552         {
2553                 if (video_ready)
2554                 {
2555                         while (ogg_stream_packetpeek(&video_in_stream, NULL) != 1) // get as many pages as needed for one package
2556                         {
2557                                 if (!video_file->ogg_get_next_page(video_file->tf->videosync, video_file->tf->to.serialno, &video_file->tf->videopage))
2558                                 {
2559                                         // We are at the end of our file, see if it is more and open more if there is
2560                                         if (local_current_package < total_packages)
2561                                         {
2562                                                 frame_offset = current_frame +1;
2563                                                 ogg_stream_clear(&video_in_stream);
2564                                                 video_file_gen->close_file();
2565                                                 delete video_file_gen;
2566                                                 delete video_asset;
2567                                                 video_asset = new Asset(packages[local_current_package]->path);
2568                                                 local_current_package++;
2570                                                 video_file_gen = new File();
2571                                                 video_file_gen->open_file(preferences, 
2572                                                         video_asset, 
2573                                                         1, //rd 
2574                                                         0, //wr
2575                                                         0, //base sample rate
2576                                                         0); // base_frame rate
2577                                                 video_file = (FileOGG*) video_file_gen->file;
2578                                                 ogg_stream_init(&video_in_stream, video_file->tf->to.serialno);
2579                                                 int64_t fp   = 0;
2580                                                 video_file->ogg_seek_to_databegin(video_file->tf->videosync, video_file->tf->to.serialno);
2582                                         } else
2583                                                 video_ready = 0;
2584                                         break;
2585                                 }
2586                                 ogg_stream_pagein(&video_in_stream, &video_file->tf->videopage);
2587                         }
2588                         while (ogg_stream_packetpeek(&video_in_stream, NULL) == 1) // get all packets out of the page
2589                         {
2590                                 ogg_stream_packetout(&video_in_stream, &op);
2591                                 if (local_current_package != total_packages) // keep it from closing the stream
2592                                         op.e_o_s = 0;
2593                                 if (video_packetno != 1)                     // if this is not the first video package do not start with b_o_s
2594                                         op.b_o_s = 0;
2595                                 else
2596                                         op.b_o_s = 1;
2597                                 op.packetno = video_packetno;
2598                                 video_packetno ++;
2599                                 int64_t granulepos = op.granulepos;
2600                                 if (granulepos != -1)
2601                                 {
2602                                 // Fix granulepos!      
2603                                         int64_t rel_iframe = granulepos >> video_file->theora_keyframe_granule_shift;
2604                                         int64_t rel_pframe = granulepos - (rel_iframe << video_file->theora_keyframe_granule_shift);
2605                                         int64_t rel_current_frame = rel_iframe + rel_pframe;
2606                                         current_frame = frame_offset + rel_current_frame;
2607                                         int64_t abs_iframe = current_frame - rel_pframe;
2608                                         
2609                                         op.granulepos = (abs_iframe << video_file->theora_keyframe_granule_shift) + rel_pframe;
2610                                         
2611 //                                      printf("iframe: %i, pframe: %i, granulepos: %i, op.packetno %lli, abs_iframe: %i\n", rel_iframe, rel_pframe, granulepos, op.packetno, abs_iframe);                              
2612                                 
2613                                 }
2614                                 ogg_stream_packetin (&output_file->tf->to, &op);
2615                                 output_file->tf->v_pkg++; 
2616                         }
2617                 }
2618                 if (audio_ready)
2619                 {
2620                         while (ogg_stream_packetpeek(&audio_in_stream, NULL) != 1) // get as many pages as needed for one package
2621                         {
2622                                 if (!audio_file->ogg_get_next_page(audio_file->tf->audiosync, audio_file->tf->vo.serialno, &audio_file->tf->audiopage))
2623                                 {
2624                                         audio_ready = 0;
2625                                         break;
2626                                 }
2627                                 ogg_stream_pagein(&audio_in_stream, &audio_file->tf->audiopage);
2628                         }
2629                         while (ogg_stream_packetpeek(&audio_in_stream, NULL) == 1) // get all packets out of the page
2630                         {
2631                                 ogg_stream_packetout(&audio_in_stream, &op);
2632                                 ogg_stream_packetin (&output_file->tf->vo, &op);
2633                                 audio_packetno++;
2634                                 output_file->tf->a_pkg++; 
2635                         }
2636                 }
2637                 
2638                 output_file->flush_ogg(0);
2639                 
2640         
2641         }
2642         
2643 // flush_ogg(1) is called on file closing time...       
2644 //      output_file->flush_ogg(1);
2646 // Just prevent thet write_samples and write_frames are called
2647         output_file->final_write = 0;
2648                 
2649         if (default_asset->audio_data)
2650         {
2651                 ogg_stream_clear(&audio_in_stream);
2652                 audio_file_gen->close_file();
2653                 delete audio_file_gen;
2654                 delete audio_asset;
2655         }
2656         if (default_asset->video_data)
2657         {
2658                 ogg_stream_clear(&video_in_stream);
2659                 video_file_gen->close_file();
2660                 delete video_file_gen;
2661                 delete video_asset;
2662         }
2664         output_file_gen->close_file();
2665         delete output_file_gen;
2667 // Now delete the temp files
2668         for(int i = 0; i < total_packages; i++)
2669                 unlink(packages[i]->path);
2671         return 0;