b8e9c497ff7344d58d71934f45cc9d21eef33be6
[goodguy/history.git] / cinelerra-5.0 / cinelerra / filempeg.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  * 
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * 
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  * 
20  */
21
22 #include "asset.h"
23 #include "bcprogressbox.h"
24 #include "bcsignals.h"
25 #include "bitspopup.h"
26 #include "byteorder.h"
27 #include "clip.h"
28 #include "commercials.h"
29 #include "condition.h"
30 #include "cstrdup.h"
31 #include "edit.h"
32 #include "file.h"
33 #include "filempeg.h"
34 #include "filesystem.h"
35 #include "format.inc"
36 #include "guicast.h"
37 #include "indexfile.h"
38 #include "indexstate.h"
39 #include "language.h"
40 #include "mainerror.h"
41 #include "mwindow.h"
42 #include "pipe.h"
43 #include "preferences.h"
44 #include "removefile.h"
45 #include "vframe.h"
46 #include "videodevice.inc"
47
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51
52
53 #define HVPEG_EXE "/hveg2enc.plugin"
54 #define MJPEG_EXE "/mpeg2enc.plugin"
55
56
57 // M JPEG dependancies
58 static double frame_rate_codes[] = 
59 {
60         0,
61         24000.0/1001.0,
62         24.0,
63         25.0,
64         30000.0/1001.0,
65         30.0,
66         50.0,
67         60000.0/1001.0,
68         60.0
69 };
70
71 static double aspect_ratio_codes[] =
72 {
73         0,
74         1.0,
75         1.333,
76         1.777,
77         2.21
78 };
79
80
81
82
83
84
85
86
87 FileMPEG::FileMPEG(Asset *asset, File *file)
88  : FileBase(asset, file)
89 {
90         reset_parameters();
91 // May also be VMPEG or AMPEG if write status.
92         if(asset->format == FILE_UNKNOWN) asset->format = FILE_MPEG;
93         asset->byte_order = 0;
94         next_frame_lock = new Condition(0, "FileMPEG::next_frame_lock");
95         next_frame_done = new Condition(0, "FileMPEG::next_frame_done");
96         vcommand_line.set_array_delete();
97 }
98
99 FileMPEG::~FileMPEG()
100 {
101         close_file();
102         delete next_frame_lock;
103         delete next_frame_done;
104         vcommand_line.remove_all_objects();
105 }
106
107 void FileMPEG::get_parameters(BC_WindowBase *parent_window, 
108         Asset *asset, 
109         BC_WindowBase* &format_window,
110         int audio_options,
111         int video_options)
112 {
113         if(audio_options && asset->format == FILE_AMPEG)
114         {
115                 MPEGConfigAudio *window = new MPEGConfigAudio(parent_window, asset);
116                 format_window = window;
117                 window->create_objects();
118                 window->run_window();
119                 delete window;
120         }
121         else
122         if(video_options && asset->format == FILE_VMPEG)
123         {
124                 MPEGConfigVideo *window = new MPEGConfigVideo(parent_window, asset);
125                 format_window = window;
126                 window->create_objects();
127                 window->run_window();
128                 delete window;
129         }
130 }
131
132 int FileMPEG::check_sig(Asset *asset)
133 {
134         return mpeg3_check_sig(asset->path);
135 }
136
137 void FileMPEG::get_info(char *title_path, char *path, char *text, int len)
138 {
139         mpeg3_t *fd;
140         *text = 0;
141
142         int result = 0;
143         int zio_access = ZIO_UNBUFFERED+ZIO_SINGLE_ACCESS;
144         if( !(fd=mpeg3_zopen(title_path, path, &result,zio_access)) ) result = 1;
145         if( !result ) result = mpeg3_create_title(fd, 0);
146         if( result ) return;
147
148         char *cp = text, *ep = text + len-1;
149         if( mpeg3_has_toc(fd) ) {
150                 cp += snprintf(cp,ep-cp, _("toc path:%s\n"), path);
151                 cp += snprintf(cp,ep-cp, _("title path:\n"));
152                 for( int i=0; i<100; ++i ) {
153                         char *title_path = mpeg3_title_path(fd,i);
154                         if( !title_path ) break;
155                         cp += snprintf(cp,ep-cp, " %2d. %s\n", i+1, title_path);
156                 }
157         }
158         else
159                 cp += snprintf(cp,ep-cp, _("file path:%s\n"), path);
160         int64_t bytes = mpeg3_get_bytes(fd);
161         char string[BCTEXTLEN];
162         sprintf(string,"%ld",bytes);
163         Units::punctuate(string);
164         cp += snprintf(cp,ep-cp, _("size: %s"), string);
165
166         if( mpeg3_is_program_stream(fd) )
167           cp += snprintf(cp,ep-cp, _("  program stream\n"));
168         else if( mpeg3_is_transport_stream(fd) )
169           cp += snprintf(cp,ep-cp, _("  transport stream\n"));
170         else if( mpeg3_is_video_stream(fd) )
171           cp += snprintf(cp,ep-cp, _("  video stream\n"));
172         else if( mpeg3_is_audio_stream(fd) )
173           cp += snprintf(cp,ep-cp, _("  audio stream\n"));
174
175         int64_t sdate = mpeg3_get_source_date(fd);
176         if( !sdate ) {
177                 struct stat64 ostat;
178                 memset(&ostat,0,sizeof(struct stat64));
179                 sdate = stat64(path, &ostat) < 0 ? 0 : ostat.st_mtime;
180         }
181         time_t tm = (time_t)sdate;
182         cp += snprintf(cp,ep-cp, _("date: %s\n"), ctime(&tm));
183
184         int vtrks = mpeg3_total_vstreams(fd);
185         cp += snprintf(cp,ep-cp, _("%d video tracks\n"), vtrks);
186         for( int vtrk=0; vtrk<vtrks; ++vtrk ) {
187                 int cmdl = mpeg3_colormodel(fd, vtrk);
188                 int color_model = bc_colormodel(cmdl);
189                 char *cmodel = MPEGColorModel::cmodel_to_string(color_model);
190                 int width = mpeg3_video_width(fd, vtrk);
191                 int height = mpeg3_video_height(fd, vtrk);
192                 cp += snprintf(cp,ep-cp, _("  v%d %s %dx%d"), vtrk, cmodel, width, height);
193                 double frame_rate = mpeg3_frame_rate(fd, vtrk);
194                 int64_t frames = mpeg3_video_frames(fd, vtrk);
195                 cp += snprintf(cp,ep-cp, _(" (%5.2f), %ld frames"), frame_rate, frames);
196                 if( frame_rate > 0 ) {
197                         double secs = (double)frames / frame_rate;
198                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
199                 }
200                 *cp++ = '\n';
201         }
202         int atrks = mpeg3_total_astreams(fd);
203         cp += snprintf(cp,ep-cp, _("%d audio tracks\n"), atrks);
204         for( int atrk=0; atrk<atrks; ++atrk) {
205                 const char *format = mpeg3_audio_format(fd, atrk);
206                 cp += snprintf(cp,ep-cp, _(" a%d %s"), atrk, format);
207                 int channels = mpeg3_audio_channels(fd, atrk);
208                 int sample_rate = mpeg3_sample_rate(fd, atrk);
209                 cp += snprintf(cp,ep-cp, _(" ch%d (%d)"), channels, sample_rate);
210                 int64_t samples = mpeg3_audio_samples(fd, atrk);
211                 cp += snprintf(cp,ep-cp, " %ld",samples);
212                 int64_t nudge = mpeg3_get_audio_nudge(fd, atrk);
213                 *cp++ = nudge >= 0 ? '+' : (nudge=-nudge, '-');
214                 cp += snprintf(cp,ep-cp, _("%ld samples"),nudge);
215                 if( sample_rate > 0 ) {
216                         double secs = (double)(samples+nudge) / sample_rate;
217                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
218                 }
219                 *cp++ = '\n';
220         }
221         int stracks = mpeg3_subtitle_tracks(fd);
222         if( stracks > 0 ) {
223                 cp += snprintf(cp,ep-cp, _("%d subtitles\n"), stracks);
224         }
225         int vts_titles = mpeg3_get_total_vts_titles(fd);
226         if( vts_titles > 0 )
227                 cp += snprintf(cp,ep-cp, _("%d title sets, "), vts_titles);
228         int interleaves = mpeg3_get_total_interleaves(fd);
229         if( interleaves > 0 )
230                 cp += snprintf(cp,ep-cp, _("%d interleaves\n"), interleaves);
231         int vts_title = mpeg3_set_vts_title(fd, -1);
232         int angle = mpeg3_set_angle(fd, -1);
233         int interleave = mpeg3_set_interleave(fd, -1);
234         int program = mpeg3_set_program(fd, -1);
235         cp += snprintf(cp,ep-cp, _("current program %d = title %d, angle %d, interleave %d\n\n"),
236                 program, vts_title, angle, interleave);
237
238         ArrayList<double> cell_times;
239         int cell_no = 0; double cell_time;
240         while( !mpeg3_get_cell_time(fd, cell_no++, &cell_time) ) {
241                 cell_times.append(cell_time);
242         }
243         if( cell_times.size() > 1 ) {
244                 cp += snprintf(cp,ep-cp, _("cell times:"));
245                 for( int i=0; i<cell_times.size(); ++i ) {
246                         if( (i%4) == 0 ) *cp++ = '\n';
247                         cp += snprintf(cp,ep-cp,_("  %3d.  %8.3f"),i,cell_times.get(i));
248                 }
249                 cp += snprintf(cp,ep-cp, "\n");
250         }
251
252         int elements = mpeg3_dvb_channel_count(fd);
253         if( elements <= 0 ) return;
254         if( !mpeg3_dvb_get_system_time(fd, &sdate) ) {
255                 tm = (time_t)sdate;
256                 cp += snprintf(cp,ep-cp, _("\nsystem time: %s"), ctime_r(&tm,string));
257         }
258         cp += snprintf(cp,ep-cp, _("elements %d\n"), elements);
259
260         for( int n=0; n<elements; ++n ) {
261                 char name[16], enc[8];  int vstream, astream;
262                 int major, minor, total_astreams, total_vstreams;
263                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
264                     mpeg3_dvb_get_station_id(fd,n,&name[0]) ||
265                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
266                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) )    continue;
267                 cp += snprintf(cp,ep-cp, " %3d.%-3d %s", major, minor, &name[0]);
268                 for( int vidx=0; vidx<total_vstreams; ++vidx ) {
269                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
270                         if( vstream < 0 ) continue;
271                         cp += snprintf(cp,ep-cp, " v%d", vstream);
272                 }
273                 for( int aidx=0; aidx<total_astreams; ++aidx ) {
274                         if( mpeg3_dvb_astream_number(fd,n,aidx,&astream,&enc[0]) ) continue;
275                         if( astream < 0 ) continue;
276                         cp += snprintf(cp,ep-cp, "    a%d %s", astream, &enc[0]);
277                         int atrack = 0;
278                         for(int i=0; i<astream; ++i )
279                                 atrack += mpeg3_audio_channels(fd, i);
280                         int channels = mpeg3_audio_channels(fd, astream);
281                         cp += snprintf(cp,ep-cp, " trk %d-%d", atrack+1, atrack+channels);
282                         if( enc[0] ) cp += snprintf(cp,ep-cp," (%s)",enc);
283                 }
284                 cp += snprintf(cp,ep-cp, "\n");
285         }
286
287         for( int n=0; n<elements; ++n ) {
288                 int major, minor;
289                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ) continue;
290                 cp += snprintf(cp,ep-cp, "\n**chan %3d.%-3d\n", major, minor);
291                 int len = mpeg3_dvb_get_chan_info(fd, n, -1, 0, cp, 1023);
292                 if( len < 0 ) len = snprintf(cp,ep-cp,_("no info"));
293                 cp += len;  *cp++ = '*';  *cp++ = '*';  *cp++ = '\n';
294                 for( int ord=0; ord<0x80; ++ord ) {
295                         for( int i=0; (len=mpeg3_dvb_get_chan_info(fd,n,ord,i,cp,1023)) >= 0; ++i ) {
296                                 char *bp = cp;  cp += len;
297                                 for( int k=2; --k>=0; ) {  // skip 2 lines
298                                         while( bp<cp && *bp++!='\n' );
299                                 }
300                                 for( char *lp=bp; bp<cp; ++bp ) {  // add new lines
301                                         if( *bp == '\n' || ((bp-lp)>=60 && *bp==' ') )
302                                                 *(lp=bp) = '\n';
303                                 }
304                                 *cp++ = '\n';  *cp = 0;  // trailing new line
305                         }
306                 }
307         }
308
309         *cp = 0;
310         mpeg3_close(fd);
311         return;
312 }
313
314 int FileMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
315 {
316         channel_mask = 0;
317         if( !fd ) return -1;
318         int elements = mpeg3_dvb_channel_count(fd);
319         if( elements <= 0 ) return -1;
320
321         int pidx = -1;
322         int total_astreams = 0, total_vstreams = 0;
323         for( int n=0; pidx<0 && n<elements; ++n ) {
324                 total_astreams = total_vstreams = 0;
325                 if( mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
326                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) ) continue;
327                 if( !total_vstreams || !total_astreams ) continue;
328                 for( int i=0; pidx<0 && i<total_vstreams; ++i ) {
329                         int vstrm = -1;
330                         if( mpeg3_dvb_vstream_number(fd,n,i,&vstrm) ) continue;
331                         if( vstrm == vstream ) pidx = n;
332                 }
333         }
334         if( pidx < 0 ) return -1;
335         int ret = -1;
336         int64_t channels = 0;
337         for( int i=0; i<total_astreams; ++i ) {
338                 int astrm = -1;
339                 if( mpeg3_dvb_astream_number(fd,pidx,i,&astrm,0) ) continue;
340                 if( astrm < 0 ) continue;
341                 if( ret < 0 ) ret = astrm;
342                 if( astream > 0 ) { --astream;  continue; }
343                 int atrack = 0;
344                 for(int i=0; i<astrm; ++i )
345                         atrack += mpeg3_audio_channels(fd, i);
346                 int64_t mask = (1 << mpeg3_audio_channels(fd, astrm)) - 1;
347                 channels |= mask << atrack;
348                 if( !astream ) break;
349         }
350         channel_mask = channels;
351         return ret;
352 }
353
354 int FileMPEG::reset_parameters_derived()
355 {
356         wrote_header = 0;
357         mjpeg_out = 0;
358         mjpeg_eof = 0;
359         mjpeg_error = 0;
360         recd_fd = -1;
361         fd = 0;
362         video_out = 0;
363         prev_track = 0;
364         temp_frame = 0;
365         twolame_temp = 0;
366         twolame_out = 0;
367         twolame_allocation = 0;
368         twolame_result = 0;
369         twofp = 0;
370         twopts = 0;
371         lame_temp[0] = 0;
372         lame_temp[1] = 0;
373         lame_allocation = 0;
374         lame_global = 0;
375         lame_output = 0;
376         lame_output_allocation = 0;
377         lame_fd = 0;
378         lame_started = 0;
379         return 0;
380 }
381
382
383 int FileMPEG::open_file(int rd, int wr)
384 {
385         int result = 0;
386
387         if(rd) {
388                 char toc_name[BCTEXTLEN];
389                 result = file->preferences->get_asset_file_path(asset, toc_name);
390                 int error = 0;
391                 fd = mpeg3_open_title(asset->path, toc_name, &error);
392                 if( !fd ) {
393                         result = 1;
394                         if(error == zmpeg3_t::ERR_INVALID_TOC_VERSION) {
395                                 eprintf(_("Couldn't open %s: invalid table of contents version.\n"
396                                         "Rebuilding the table of contents."), asset->path);
397                         }
398                         else if(error == zmpeg3_t::ERR_TOC_DATE_MISMATCH) {
399                                 eprintf(_("Couldn't open %s: table of contents out of date.\n"
400                                         "Rebuilding the table of contents."), asset->path);
401                         }
402                         else {
403                                 eprintf(_("Couldn't open %s: table of contents corrupt.\n"
404                                         "Rebuilding the table of contents."), asset->path);
405                         }
406                         char filename[BCTEXTLEN];
407                         strcpy(filename, toc_name);
408                         char *sfx = strrchr(filename,'.');
409                         if( sfx && !strcmp(sfx+1,"toc") ) {
410                                 remove(filename);
411                                 strcpy(sfx+1,"idx");
412                                 remove(filename);
413                                 strcpy(toc_name, asset->path);
414                                 fd = mpeg3_open_title(asset->path, toc_name, &error);
415                                 if( fd ) result = 0;
416                         }
417                         if( result )
418                                 eprintf(_("Couldn't open %s: rebuild failed.\n"), asset->path);
419                 }
420                 if(!result) {
421 // Determine if the file needs a table of contents and create one if needed.
422 // If it has video it must be scanned since video has keyframes.
423                         if(mpeg3_total_vstreams(fd) || mpeg3_total_astreams(fd)) {
424                                 if(create_index()) return 1;
425                         }
426
427 // more than 4 doesnt help much
428                         mpeg3_set_cpus(fd, file->cpus < 4 ? file->cpus : 4);
429                         file->current_program = mpeg3_set_program(fd, -1);
430                         if( asset->program < 0 )
431                                 asset->program = file->current_program;
432
433                         asset->audio_data = mpeg3_has_audio(fd);
434                         if(asset->audio_data) {
435                                 asset->channels = 0;
436                                 for(int i = 0; i < mpeg3_total_astreams(fd); i++) {
437                                         asset->channels += mpeg3_audio_channels(fd, i);
438                                 }
439                                 if(!asset->sample_rate)
440                                         asset->sample_rate = mpeg3_sample_rate(fd, 0);
441                                 asset->audio_length = mpeg3_audio_samples(fd, 0);
442                                 if(!asset->channels || 
443                                         !asset->sample_rate)
444                                         result = 1;
445                         }
446
447                         asset->video_data = mpeg3_has_video(fd);
448                         if(asset->video_data) {
449                                 if( !asset->layers ) {
450                                         asset->layers = mpeg3_total_vstreams(fd);
451                                 }
452                                 asset->actual_width = mpeg3_video_width(fd, 0);
453                                 if( !asset->width )
454                                         asset->width = asset->actual_width;
455                                 asset->actual_height = mpeg3_video_height(fd, 0);
456                                 if( !asset->height )
457                                         asset->height = asset->actual_height;
458                                 if( !asset->video_length )
459                                         asset->video_length = mpeg3_video_frames(fd, 0);
460                                 if( !asset->vmpeg_cmodel )
461                                         asset->vmpeg_cmodel = bc_colormodel(mpeg3_colormodel(fd, 0));
462                                 if( !asset->frame_rate )
463                                         asset->frame_rate = mpeg3_frame_rate(fd, 0);
464                         }
465                 }
466         }
467
468
469         
470         if(!result && wr && asset->format == FILE_VMPEG)
471         {
472 // Heroine Virtual encoder
473 //  this one is cinelerra-x.x.x/mpeg2enc
474                 if(asset->vmpeg_cmodel == BC_YUV422P)
475                 {
476                         char bitrate_string[BCTEXTLEN];
477                         char quant_string[BCTEXTLEN];
478                         char iframe_string[BCTEXTLEN];
479
480                         sprintf(bitrate_string, "%d", asset->vmpeg_bitrate);
481                         sprintf(quant_string, "%d", asset->vmpeg_quantization);
482                         sprintf(iframe_string, "%d", asset->vmpeg_iframe_distance);
483
484 // Construct command line
485                         if(!result)
486                         {
487                                 char string[BCTEXTLEN];  string[0] = 0;
488                                 sprintf(mjpeg_command, "%s%s", 
489                                         file->preferences->plugin_dir, HVPEG_EXE);
490                                 append_vcommand_line(string);
491
492                                 if(asset->aspect_ratio > 0)
493                                 {
494                                         append_vcommand_line("-a");
495 // Square pixels
496                                         if(EQUIV((double)asset->width / asset->height,
497                                                 asset->aspect_ratio))
498                                                 append_vcommand_line("1");
499                                         else
500                                         if(EQUIV(asset->aspect_ratio, 1.333))
501                                                 append_vcommand_line("2");
502                                         else
503                                         if(EQUIV(asset->aspect_ratio, 1.777))
504                                                 append_vcommand_line("3");
505                                         else
506                                         if(EQUIV(asset->aspect_ratio, 2.11))
507                                                 append_vcommand_line("4");
508                                 }
509
510                                 append_vcommand_line(asset->vmpeg_derivative == 1 ? "-1" : "");
511                                 append_vcommand_line(asset->vmpeg_cmodel == BC_YUV422P ? "-422" : "");
512                                 if(asset->vmpeg_fix_bitrate)
513                                 {
514                                         append_vcommand_line("-b");
515                                         append_vcommand_line(bitrate_string);
516                                 }
517                                 else
518                                 {
519                                         append_vcommand_line("-q");
520                                         append_vcommand_line(quant_string);
521                                 }
522                                 append_vcommand_line("-n");
523                                 append_vcommand_line(iframe_string);
524                                 append_vcommand_line(asset->vmpeg_progressive ? "-p" : "");
525                                 append_vcommand_line(asset->vmpeg_denoise ? "-d" : "");
526                                 append_vcommand_line(file->cpus <= 1 ? "-u" : "");
527                                 append_vcommand_line(asset->vmpeg_seq_codes ? "-g" : "");
528                                 append_vcommand_line(asset->path);
529
530                                 video_out = new FileMPEGVideo(this);
531                                 video_out->start();
532                         }
533                 }
534                 else
535 // mjpegtools encoder
536 //  this one is cinelerra-x.x.x/thirdparty/mjpegtools/mpeg2enc
537                 {
538                         sprintf(mjpeg_command, "%s%s -v 0 ", 
539                                 file->preferences->plugin_dir, MJPEG_EXE);
540
541 // Must disable interlacing if MPEG-1
542                         switch (asset->vmpeg_preset)
543                         {
544                                 case 0: asset->vmpeg_progressive = 1; break;
545                                 case 1: asset->vmpeg_progressive = 1; break;
546                                 case 2: asset->vmpeg_progressive = 1; break;
547                         }
548
549
550
551 // The current usage of mpeg2enc requires bitrate of 0 when quantization is fixed and
552 // quantization of 1 when bitrate is fixed.  Perfectly intuitive.
553                         char string[BCTEXTLEN];
554                         if(asset->vmpeg_fix_bitrate)
555                         {
556                                 sprintf(string, " -b %d -q 1", asset->vmpeg_bitrate / 1000);
557                         }
558                         else
559                         {
560                                 sprintf(string, " -b 0 -q %d", asset->vmpeg_quantization);
561                         }
562                         strcat(mjpeg_command, string);
563
564
565
566
567
568
569 // Aspect ratio
570                         int aspect_ratio_code = -1;
571                         if(asset->aspect_ratio > 0)
572                         {
573                                 int ncodes = sizeof(aspect_ratio_codes) / sizeof(double);
574                                 for(int i = 1; i < ncodes; i++)
575                                 {
576                                         if(EQUIV(aspect_ratio_codes[i], asset->aspect_ratio))
577                                         {
578                                                 aspect_ratio_code = i;
579                                                 break;
580                                         }
581                                 }
582                         }
583
584
585 // Square pixels
586                         if(EQUIV((double)asset->width / asset->height, asset->aspect_ratio))
587                                 aspect_ratio_code = 1;
588                         
589                         if(aspect_ratio_code < 0)
590                         {
591                                 eprintf(_("Unsupported aspect ratio %f\n"), asset->aspect_ratio);
592                                 aspect_ratio_code = 2;
593                         }
594                         sprintf(string, " -a %d", aspect_ratio_code);
595                         strcat(mjpeg_command, string);
596
597
598
599
600
601
602 // Frame rate
603                         int frame_rate_code = -1;
604                         int ncodes = sizeof(frame_rate_codes) / sizeof(double);
605                         for(int i = 1; i < ncodes; ++i)
606                         {
607                                 if(EQUIV(asset->frame_rate, frame_rate_codes[i]))
608                                 {
609                                         frame_rate_code = i;
610                                         break;
611                                 }
612                         }
613                         if(frame_rate_code < 0)
614                         {
615                                 frame_rate_code = 4;
616                                 eprintf(_("Unsupported frame rate %f\n"), asset->frame_rate);
617                         }
618                         sprintf(string, " -F %d", frame_rate_code);
619                         strcat(mjpeg_command, string);
620
621
622
623
624
625                         strcat(mjpeg_command, 
626                                 asset->vmpeg_progressive ? " -I 0" : " -I 1");
627                         
628
629
630                         sprintf(string, " -M %d", file->cpus);
631                         strcat(mjpeg_command, string);
632
633
634                         if(!asset->vmpeg_progressive)
635                         {
636                                 strcat(mjpeg_command, asset->vmpeg_field_order ? " -z b" : " -z t");
637                         }
638
639
640                         sprintf(string, " -f %d", asset->vmpeg_preset);
641                         strcat(mjpeg_command, string);
642
643
644                         sprintf(string, " -g %d -G %d", asset->vmpeg_iframe_distance, asset->vmpeg_iframe_distance);
645                         strcat(mjpeg_command, string);
646
647
648                         if(asset->vmpeg_seq_codes) strcat(mjpeg_command, " -s");
649
650
651                         sprintf(string, " -R %d", CLAMP(asset->vmpeg_pframe_distance, 0, 2));
652                         strcat(mjpeg_command, string);
653
654                         sprintf(string, " -o '%s'", asset->path);
655                         strcat(mjpeg_command, string);
656
657
658
659                         printf("FileMPEG::open_file: Running %s\n", mjpeg_command);
660                         if(!(mjpeg_out = popen(mjpeg_command, "w")))
661                         {
662                                 perror("FileMPEG::open_file");
663                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), mjpeg_command);
664                                 return 1;
665                         }
666
667                         video_out = new FileMPEGVideo(this);
668                         video_out->start();
669                 }
670         }
671         else
672         if(wr && asset->format == FILE_AMPEG)
673         {
674                 //char encoder_string[BCTEXTLEN]; encoder_string[0] = 0;
675 //printf("FileMPEG::open_file 1 %d\n", asset->ampeg_derivative);
676
677                 if(asset->ampeg_derivative == 2)
678                 {
679                         twofp = fopen(asset->path, "w" );
680                         if( !twofp ) return 1;
681                         twopts = twolame_init();
682                         int channels = asset->channels >= 2 ? 2 : 1;
683                         twolame_set_num_channels(twopts, channels);
684                         twolame_set_in_samplerate(twopts, asset->sample_rate);
685                         twolame_set_mode(twopts, channels >= 2 ?
686                                 TWOLAME_JOINT_STEREO : TWOLAME_MONO);
687                         twolame_set_bitrate(twopts, asset->ampeg_bitrate);
688                         twolame_init_params(twopts);
689                 }
690                 else
691                 if(asset->ampeg_derivative == 3)
692                 {
693                         lame_global = lame_init();
694 //                      lame_set_brate(lame_global, asset->ampeg_bitrate / 1000);
695                         lame_set_brate(lame_global, asset->ampeg_bitrate);
696                         lame_set_quality(lame_global, 0);
697                         lame_set_in_samplerate(lame_global, 
698                                 asset->sample_rate);
699                         lame_set_num_channels(lame_global,
700                                 asset->channels);
701                         if((result = lame_init_params(lame_global)) < 0)
702                         {
703                                 eprintf(_("encode: lame_init_params returned %d\n"), result);
704                                 lame_close(lame_global);
705                                 lame_global = 0;
706                         }
707                         else
708                         if(!(lame_fd = fopen(asset->path, "w")))
709                         {
710                                 perror("FileMPEG::open_file");
711                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
712                                 lame_close(lame_global);
713                                 lame_global = 0;
714                                 result = 1;
715                         }
716                 }
717                 else
718                 {
719                         eprintf(_("ampeg_derivative=%d\n"), asset->ampeg_derivative);
720                         result = 1;
721                 }
722         }
723
724 // Transport stream for DVB capture
725         if(!result && !rd && !wr && asset->format == FILE_MPEG)
726         {
727                 if( (recd_fd = open(asset->path, O_CREAT+O_TRUNC+O_WRONLY,
728                         S_IRUSR+S_IWUSR + S_IRGRP+S_IWGRP)) < 0 )
729                 {
730                         perror("FileMPEG::open_file");
731                         eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
732                         result = 1;
733                 }
734         }
735
736
737 //asset->dump();
738         return result;
739 }
740
741
742
743
744
745 int FileMPEG::set_skimming(int track, int skim, skim_fn fn, void *vp)
746 {
747         return !fn ? mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0) :
748                 mpeg3_set_thumbnail_callback(fd, track, skim, 1, fn, vp);
749 }
750
751 int FileMPEG::skimming(void *vp, int track)
752 {
753         File *file = (File *)vp;
754         FileMPEG *mpeg = (FileMPEG *)file->file;
755         return mpeg->skim_result = mpeg->skim_callback(mpeg->skim_data, track);
756 }
757
758 int FileMPEG::skim_video(int track, void *vp, skim_fn fn)
759 {
760         skim_callback = fn;  skim_data = vp;
761         mpeg3_set_thumbnail_callback(fd, track, 1, 1, skimming, (void*)file);
762         skim_result = -1;
763         while( skim_result < 0 && !mpeg3_end_of_video(fd, track) )
764                 mpeg3_drop_frames(fd, 1, track);
765         mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0);
766         return skim_result;
767 }
768
769
770
771 int FileMPEG::toc_nail(void *vp, int track)
772 {
773         File *file = (File *)vp;
774         FileMPEG *mpeg = (FileMPEG *)file->file;
775         int64_t framenum; uint8_t *tdat; int mw, mh;
776         if( mpeg->get_thumbnail(track, framenum, tdat, mw, mh) ) return 1;
777         int pid, width, height;  double framerate;
778         if( mpeg->get_video_info(track, pid, framerate, width, height) ) return 1;
779         if( pid < 0 || framerate <= 0 ) return 1;
780         double position = framenum / framerate;
781 //printf("t%d/%03x f"_LD", %dx%d %dx%d\n",track,pid,framenum,mw,mh,width,height);
782         MWindow::commercials->get_frame(file, pid, position, tdat, mw, mh, width, height);
783         return 0;
784 }
785
786
787 int FileMPEG::create_index()
788 {
789 // Calculate TOC path
790         char index_filename[BCTEXTLEN];
791         char source_filename[BCTEXTLEN];
792
793         IndexFile::get_index_filename(source_filename, 
794                 file->preferences->index_directory, 
795                 index_filename, 
796                 asset->path);
797         char *ptr = strrchr(index_filename, '.');
798         int error = 0;
799
800         if(!ptr) return 1;
801
802 // File is a table of contents.
803         if(fd && mpeg3_has_toc(fd)) return 0;
804
805         sprintf(ptr, ".toc");
806
807         int need_toc = 1;
808
809         if(fd) mpeg3_close(fd);
810         fd = 0;
811
812 // Test existing copy of TOC
813         if((fd = mpeg3_open_title(asset->path, index_filename, &error)))
814                 need_toc = 0;
815
816         if(need_toc)
817         {
818                 int result = 0;
819 // Create progress window.
820 // This gets around the fact that MWindowGUI is locked.
821                 int64_t total_bytes = 0, last_bytes = -1;
822                 fd = mpeg3_start_toc( asset->path, index_filename,
823                                 file->current_program, &total_bytes);
824                 if( !fd ) {
825                         eprintf(_("cant init toc index\n"));
826                         result = 1;
827                 }
828
829                 struct timeval new_time, prev_time, start_time, current_time;
830                 gettimeofday(&prev_time, 0);  gettimeofday(&start_time, 0);
831
832                 if( !result && file->preferences->scan_commercials ) {
833                         set_skimming(-1, 1, toc_nail, file);
834                         if( (result=MWindow::commercials->resetDb() ) != 0 )
835                                 eprintf(_("cant access commercials database"));
836                 }
837
838                 char progress_title[BCTEXTLEN];  progress_title[0] = 0;
839                 BC_ProgressBox *progress = 0;
840                 if( !result ) {
841                         sprintf(progress_title, _("Creating %s\n"), index_filename);
842                         progress = new BC_ProgressBox(-1, -1,
843                                         progress_title, total_bytes);
844                         progress->start();
845                 }
846
847                 while( !result ) {
848                         int64_t bytes_processed = 0;
849                         if( mpeg3_do_toc(fd, &bytes_processed) ) break;
850                         gettimeofday(&new_time, 0);
851
852                         if(new_time.tv_sec - prev_time.tv_sec >= 1)
853                         {
854                                 gettimeofday(&current_time, 0);
855                                 int64_t elapsed_seconds = current_time.tv_sec - start_time.tv_sec;
856                                 int64_t total_seconds = !bytes_processed ? 0 :
857                                   elapsed_seconds * total_bytes / bytes_processed;
858                                 int64_t eta = total_seconds - elapsed_seconds;
859                                 progress->update(bytes_processed, 1);
860                                 char string[BCTEXTLEN];
861                                 sprintf(string, "%sETA: " _LD "m" _LD "s",
862                                         progress_title, eta / 60, eta % 60);
863                                 progress->update_title(string, 1);
864 //                              fprintf(stderr, "ETA: %dm%ds        \r", 
865 //                                      bytes_processed * 100 / total_bytes,
866 //                                      eta / 60, eta % 60);
867 //                              fflush(stdout);
868                                 prev_time = new_time;
869                         }
870                         if(bytes_processed >= total_bytes) break;
871                         if(progress->is_cancelled()) result = 1;
872                         if( bytes_processed == last_bytes ) {
873                                 eprintf(_("toc scan stopped before eof"));
874                                 break;
875                         }
876                         last_bytes = bytes_processed;
877                 }
878
879                 // record scan results
880                 if( file->preferences->scan_commercials ) {
881                         if( !result ) MWindow::commercials->write_ads(asset->path);
882                         MWindow::commercials->closeDb();
883                 }
884
885                 if( fd ) { mpeg3_stop_toc(fd);  fd = 0; }
886                 if( progress ) { progress->stop_progress(); delete progress; }
887                 if( result ) { remove_file(index_filename); return 1; }
888         }
889
890
891
892 // Reopen file from index path instead of asset path.
893         if(!fd)
894         {
895                 if(!(fd = mpeg3_open(index_filename, &error)))
896                 {
897                         return 1;
898                 }
899         }
900
901         return 0;
902 }
903
904
905
906
907
908
909 void FileMPEG::append_vcommand_line(const char *string)
910 {
911         if(string[0])
912         {
913                 char *argv = cstrdup(string);
914                 vcommand_line.append(argv);
915         }
916 }
917
918 int FileMPEG::close_file()
919 {
920         mjpeg_eof = 1;
921         next_frame_lock->unlock();
922
923         if(fd)
924         {
925                 mpeg3_close(fd);
926         }
927
928         if(video_out)
929         {
930 // End of sequence signal
931                 if(file->asset->vmpeg_cmodel == BC_YUV422P)
932                 {
933                         mpeg2enc_set_input_buffers(1, 0, 0, 0);
934                 }
935                 delete video_out;
936                 video_out = 0;
937         }
938
939         vcommand_line.remove_all_objects();
940
941         if(twofp) {
942                 unsigned char opkt[1152*2]; 
943                 int ret = twolame_encode_flush(twopts, opkt, sizeof(opkt));
944                 if( ret > 0 )
945                         fwrite(opkt, 1, ret, twofp);
946                 else if( ret < 0 )
947                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
948                 fclose(twofp);  twofp = 0;
949         }
950         if( twopts ) { twolame_close(&twopts); twopts = 0; }
951
952         if(lame_global)
953                 lame_close(lame_global);
954
955         if(temp_frame) delete temp_frame;
956         if(twolame_temp) delete [] twolame_temp;
957
958         if(lame_temp[0]) delete [] lame_temp[0];
959         if(lame_temp[1]) delete [] lame_temp[1];
960         if(lame_output) delete [] lame_output;
961         if(lame_fd) fclose(lame_fd);
962
963         if(mjpeg_out) pclose(mjpeg_out);
964
965         if( recd_fd >= 0 ) {
966                 close(recd_fd);
967                 recd_fd = -1;
968         }
969
970         reset_parameters();
971
972         FileBase::close_file();
973         return 0;
974 }
975
976 int FileMPEG::get_best_colormodel(Asset *asset, int driver)
977 {
978 //printf("FileMPEG::get_best_colormodel 1\n");
979         switch(driver)
980         {
981                 case PLAYBACK_X11:
982                         return BC_RGB888;
983                 case PLAYBACK_X11_XV:
984                 case PLAYBACK_ASYNCHRONOUS:
985                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
986                                 asset->vmpeg_cmodel : BC_RGB888;
987                 case PLAYBACK_X11_GL:
988                         return BC_YUV888;
989                 case PLAYBACK_LML:
990                 case PLAYBACK_BUZ:
991                         return BC_YUV422P;
992                 case PLAYBACK_DV1394:
993                 case PLAYBACK_FIREWIRE:
994                         return BC_YUV422P;
995                 case VIDEO4LINUX:
996                 case VIDEO4LINUX2:
997                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
998                                 asset->vmpeg_cmodel : BC_RGB888;
999                 case VIDEO4LINUX2JPEG:
1000                         return BC_COMPRESSED;
1001                 case CAPTURE_DVB:
1002                 case VIDEO4LINUX2MPEG:
1003                         return BC_YUV422P;
1004                 case CAPTURE_JPEG_WEBCAM:
1005                         return BC_COMPRESSED;
1006                 case CAPTURE_YUYV_WEBCAM:
1007                         return BC_YUV422;
1008                 case CAPTURE_BUZ:
1009                 case CAPTURE_LML:
1010                         return BC_YUV422;
1011                 case CAPTURE_FIREWIRE:
1012                 case CAPTURE_IEC61883:
1013                         return BC_YUV422P;
1014         }
1015         eprintf(_("unknown driver %d\n"),driver);
1016         return BC_RGB888;
1017 }
1018
1019 int FileMPEG::colormodel_supported(int colormodel)
1020 {
1021         return colormodel;
1022 }
1023
1024 int FileMPEG::get_index(char *index_path)
1025 {
1026         if(!fd) return 1;
1027
1028
1029 // Convert the index tables from tracks to channels.
1030         if(mpeg3_index_tracks(fd)) {
1031                 IndexState *index_state = asset->index_state;
1032                 int index_zoom = mpeg3_index_zoom(fd);
1033                 int ntracks = mpeg3_index_tracks(fd);
1034                 int64_t offset = 0;
1035                 for(int i = 0; i < ntracks; i++) {
1036                         int nch = mpeg3_index_channels(fd, i);
1037                         for(int j = 0; j < nch; j++) {
1038                                 float *bfr = (float *)mpeg3_index_data(fd, i, j);
1039                                 int64_t size = 2*mpeg3_index_size(fd, i);
1040                                 index_state->add_index_entry(bfr, offset, size);
1041                                 offset += size;
1042                         }
1043                 }
1044                 FileSystem fs;
1045                 int64_t file_bytes = fs.get_size(asset->path);
1046                 return index_state->write_index(index_path, asset, index_zoom, file_bytes);
1047         }
1048
1049         return 1;
1050 }
1051
1052
1053 int FileMPEG::can_copy_from(Asset *asset, int64_t position)
1054 {
1055         if(!fd) return 0;
1056         return 0;
1057 }
1058
1059 int FileMPEG::set_audio_position(int64_t sample)
1060 {
1061 #if 0
1062         if(!fd) return 1;
1063         
1064         int channel, stream;
1065         to_streamchannel(file->current_channel, stream, channel);
1066
1067 //printf("FileMPEG::set_audio_position %d %d %d\n", sample, mpeg3_get_sample(fd, stream), last_sample);
1068         if(sample != mpeg3_get_sample(fd, stream) &&
1069                 sample != last_sample)
1070         {
1071                 if(sample >= 0 && sample < asset->audio_length)
1072                 {
1073 //printf("FileMPEG::set_audio_position seeking stream %d\n", sample);
1074                         return mpeg3_set_sample(fd, sample, stream);
1075                 }
1076                 else
1077                         return 1;
1078         }
1079 #endif
1080         return 0;
1081 }
1082
1083 int FileMPEG::set_video_position(int64_t pos)
1084 {
1085         if( !fd || pos < 0 || pos >= asset->video_length )
1086                 return 1;
1087 //printf("FileMPEG::set_video_position 1 " _LD "\n", x);
1088         mpeg3_set_frame(fd, pos, file->current_layer);
1089         return 0;
1090 }
1091
1092 int64_t FileMPEG::get_memory_usage()
1093 {
1094         int64_t result = file->rd && fd ? mpeg3_memory_usage(fd) : 0;
1095 //printf("FileMPEG::get_memory_usage %d  " _LD "\n", __LINE__, result);
1096         return result;
1097 }
1098
1099 int FileMPEG::set_program(int no)
1100 {
1101         return fd ? mpeg3_set_program(fd, no) : -1;
1102 }
1103
1104 int FileMPEG::get_cell_time(int no, double &time)
1105 {
1106         return fd ? mpeg3_get_cell_time(fd, no, &time) : -1;
1107 }
1108
1109 int FileMPEG::get_system_time(int64_t &tm)
1110 {
1111         return fd ? mpeg3_dvb_get_system_time(fd, &tm) : -1;
1112 }
1113
1114 int FileMPEG::get_video_pid(int track)
1115 {
1116         return fd ? mpeg3_video_pid(fd, track) : -1;
1117 }
1118
1119 int FileMPEG::get_video_info(int track, int &pid,
1120                 double &framerate, int &width, int &height, char *title)
1121 {
1122         if( !fd ) return -1;
1123         pid = mpeg3_video_pid(fd, track);
1124         framerate = mpeg3_frame_rate(fd, track);
1125         width = mpeg3_video_width(fd, track);
1126         height = mpeg3_video_height(fd, track);
1127         if( !title ) return 0;
1128         *title = 0;
1129
1130         int elements = mpeg3_dvb_channel_count(fd);
1131         for( int n=0; n<elements; ++n ) {
1132                 int major, minor, total_vstreams, vstream, vidx;
1133                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
1134                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ) continue;
1135                 for( vidx=0; vidx<total_vstreams; ++vidx ) {
1136                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
1137                         if( vstream < 0 ) continue;
1138                         if( vstream == track ) {
1139                                 sprintf(title, "%3d.%-3d", major, minor);
1140                                 return 0;
1141                         }
1142                 }
1143         }
1144         return 0;
1145 }
1146
1147 int FileMPEG::select_video_stream(Asset *asset, int vstream)
1148 {
1149         if( !fd ) return -1;
1150         asset->width = mpeg3_video_width(fd, vstream);
1151         asset->height = mpeg3_video_height(fd, vstream);
1152         asset->video_length = mpeg3_video_frames(fd, vstream);
1153         asset->frame_rate = mpeg3_frame_rate(fd, vstream);
1154         return 0;
1155 }
1156
1157 int FileMPEG::select_audio_stream(Asset *asset, int astream)
1158 {
1159         if( !fd ) return -1;
1160         asset->sample_rate = mpeg3_sample_rate(fd, astream);
1161         asset->audio_length = mpeg3_audio_samples(fd, astream);
1162         return 0;
1163 }
1164
1165 int FileMPEG::get_thumbnail(int stream,
1166         int64_t &position, unsigned char *&thumbnail, int &ww, int &hh)
1167 {
1168         return !fd ? -1 :
1169                 mpeg3_get_thumbnail(fd, stream, &position, &thumbnail, &ww, &hh);
1170 }
1171
1172 int FileMPEG::write_samples(double **buffer, int64_t len)
1173 {
1174         int result = 0;
1175
1176 //printf("FileMPEG::write_samples 1\n");
1177         if(asset->ampeg_derivative == 2) {
1178 // Convert to int16
1179                 int channels = MIN(asset->channels, 2);
1180                 int64_t audio_size = len * channels * 2;
1181                 if(twolame_allocation < audio_size) {
1182                         if(twolame_temp) delete [] twolame_temp;
1183                         twolame_temp = new unsigned char[audio_size];
1184                         twolame_allocation = audio_size;
1185                         if(twolame_out) delete [] twolame_out;
1186                         twolame_out = new unsigned char[audio_size + 1152];
1187                 }
1188
1189                 for(int i = 0; i < channels; i++) {
1190                         int16_t *output = ((int16_t*)twolame_temp) + i;
1191                         double *input = buffer[i];
1192                         for(int j = 0; j < len; j++) {
1193                                 int sample = (int)(*input * 0x7fff);
1194                                 *output = (int16_t)(CLIP(sample, -0x8000, 0x7fff));
1195                                 output += channels;
1196                                 input++;
1197                         }
1198                 }
1199                 int ret = twolame_encode_buffer_interleaved(twopts,
1200                                 (int16_t*)twolame_temp, len,
1201                                 twolame_out, twolame_allocation+1152);
1202                 if( ret > 0 )
1203                         fwrite(twolame_out, 1, ret, twofp);
1204                 else if( ret < 0 )
1205                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
1206         }
1207         else
1208         if(asset->ampeg_derivative == 3)
1209         {
1210                 int channels = MIN(asset->channels, 2);
1211                 int64_t audio_size = len * channels;
1212                 if(!lame_global) return 1;
1213                 if(!lame_fd) return 1;
1214                 if(lame_allocation < audio_size)
1215                 {
1216                         if(lame_temp[0]) delete [] lame_temp[0];
1217                         if(lame_temp[1]) delete [] lame_temp[1];
1218                         lame_temp[0] = new float[audio_size];
1219                         lame_temp[1] = new float[audio_size];
1220                         lame_allocation = audio_size;
1221                 }
1222
1223                 if(lame_output_allocation < audio_size * 4)
1224                 {
1225                         if(lame_output) delete [] lame_output;
1226                         lame_output_allocation = audio_size * 4;
1227                         lame_output = new char[lame_output_allocation];
1228                 }
1229
1230                 for(int i = 0; i < channels; i++)
1231                 {
1232                         float *output = lame_temp[i];
1233                         double *input = buffer[i];
1234                         for(int j = 0; j < len; j++)
1235                         {
1236                                 *output++ = *input++ * (float)32768;
1237                         }
1238                 }
1239
1240                 result = lame_encode_buffer_float(lame_global,
1241                         lame_temp[0],
1242                         (channels > 1) ? lame_temp[1] : lame_temp[0],
1243                         len,
1244                         (unsigned char*)lame_output,
1245                         lame_output_allocation);
1246                 if(result > 0)
1247                 {
1248                         char *real_output = lame_output;
1249                         int bytes = result;
1250                         if(!lame_started)
1251                         {
1252                                 for(int i = 0; i < bytes; i++)
1253                                         if(lame_output[i])
1254                                         {
1255                                                 real_output = &lame_output[i];
1256                                                 lame_started = 1;
1257                                                 bytes -= i;
1258                                                 break;
1259                                         }
1260                         }
1261                         if(bytes > 0 && lame_started)
1262                         {
1263                                 result = !fwrite(real_output, 1, bytes, lame_fd);
1264                                 if(result) {
1265                                         perror("FileMPEG::write_samples");
1266                                         eprintf(_("write failed: %m"));
1267                                 }
1268                         }
1269                         else
1270                                 result = 0;
1271                 }
1272                 else
1273                         result = 1;
1274         }
1275
1276         return result;
1277 }
1278
1279 int FileMPEG::write_frames(VFrame ***frames, int len)
1280 {
1281         int result = 0;
1282
1283         if(video_out)
1284         {
1285                 int temp_w = (int)((asset->width + 15) / 16) * 16;
1286                 int temp_h;
1287
1288                 int output_cmodel = asset->vmpeg_cmodel;
1289 // verify colormodel supported in MPEG output
1290                 switch( output_cmodel ) {
1291                 case BC_YUV420P:
1292                 case BC_YUV422P:
1293                         break;
1294                 default:
1295                         return 1;
1296                 }
1297                 
1298 // Height depends on progressiveness
1299                 if(asset->vmpeg_progressive || asset->vmpeg_derivative == 1)
1300                         temp_h = (int)((asset->height + 15) / 16) * 16;
1301                 else
1302                         temp_h = (int)((asset->height + 31) / 32) * 32;
1303
1304 //printf("FileMPEG::write_frames 1\n");
1305                 
1306 // Only 1 layer is supported in MPEG output
1307                 for(int i = 0; i < 1; i++)
1308                 {
1309                         for(int j = 0; j < len && !result; j++)
1310                         {
1311                                 VFrame *frame = frames[i][j];
1312                                 
1313                                 
1314                                 
1315                                 if(asset->vmpeg_cmodel == BC_YUV422P)
1316                                 {
1317                                         if(frame->get_w() == temp_w &&
1318                                                 frame->get_h() == temp_h &&
1319                                                 frame->get_color_model() == output_cmodel)
1320                                         {
1321                                                 mpeg2enc_set_input_buffers(0, 
1322                                                         (char*)frame->get_y(),
1323                                                         (char*)frame->get_u(),
1324                                                         (char*)frame->get_v());
1325                                         }
1326                                         else
1327                                         {
1328                                                 if(temp_frame &&
1329                                                         (temp_frame->get_w() != temp_w ||
1330                                                         temp_frame->get_h() != temp_h ||
1331                                                         temp_frame->get_color_model() || output_cmodel))
1332                                                 {
1333                                                         delete temp_frame;
1334                                                         temp_frame = 0;
1335                                                 }
1336
1337
1338                                                 if(!temp_frame)
1339                                                 {
1340                                                         temp_frame = new VFrame(0, 
1341                                                                 -1,
1342                                                                 temp_w, 
1343                                                                 temp_h, 
1344                                                                 output_cmodel,
1345                                                                 -1);
1346                                                 }
1347
1348                                                 BC_CModels::transfer(temp_frame->get_rows(), 
1349                                                         frame->get_rows(),
1350                                                         temp_frame->get_y(),
1351                                                         temp_frame->get_u(),
1352                                                         temp_frame->get_v(),
1353                                                         frame->get_y(),
1354                                                         frame->get_u(),
1355                                                         frame->get_v(),
1356                                                         0,
1357                                                         0,
1358                                                         frame->get_w(),
1359                                                         frame->get_h(),
1360                                                         0,
1361                                                         0,
1362                                                         temp_frame->get_w(),
1363                                                         temp_frame->get_h(),
1364                                                         frame->get_color_model(), 
1365                                                         temp_frame->get_color_model(),
1366                                                         0, 
1367                                                         frame->get_w(),
1368                                                         temp_frame->get_w());
1369
1370                                                 mpeg2enc_set_input_buffers(0, 
1371                                                         (char*)temp_frame->get_y(),
1372                                                         (char*)temp_frame->get_u(),
1373                                                         (char*)temp_frame->get_v());
1374                                         }
1375                                 }
1376                                 else
1377                                 {
1378 // MJPEG uses the same dimensions as the input
1379 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1380                                         if(frame->get_color_model() == output_cmodel)
1381                                         {
1382                                                 mjpeg_y = frame->get_y();
1383                                                 mjpeg_u = frame->get_u();
1384                                                 mjpeg_v = frame->get_v();
1385                                         }
1386                                         else
1387                                         {
1388 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1389                                                 if(!temp_frame)
1390                                                 {
1391                                                         temp_frame = new VFrame(0, 
1392                                                                 -1,
1393                                                                 asset->width, 
1394                                                                 asset->height, 
1395                                                                 output_cmodel,
1396                                                                 -1);
1397                                                 }
1398
1399 // printf("FileMPEG::write_frames %d temp_frame=%p %p %p %p frame=%p %p %p %p color_model=%p %p\n", 
1400 // __LINE__,
1401 // temp_frame,
1402 // temp_frame->get_w(),
1403 // temp_frame->get_h(),
1404 // frame,
1405 // frame->get_w(),
1406 // frame->get_h(),
1407 // temp_frame->get_color_model(),
1408 // frame->get_color_model()); sleep(1);
1409                                                 BC_CModels::transfer(temp_frame->get_rows(), 
1410                                                         frame->get_rows(),
1411                                                         temp_frame->get_y(),
1412                                                         temp_frame->get_u(),
1413                                                         temp_frame->get_v(),
1414                                                         frame->get_y(),
1415                                                         frame->get_u(),
1416                                                         frame->get_v(),
1417                                                         0,
1418                                                         0,
1419                                                         frame->get_w(),
1420                                                         frame->get_h(),
1421                                                         0,
1422                                                         0,
1423                                                         temp_frame->get_w(),
1424                                                         temp_frame->get_h(),
1425                                                         frame->get_color_model(), 
1426                                                         temp_frame->get_color_model(),
1427                                                         0, 
1428                                                         frame->get_w(),
1429                                                         temp_frame->get_w());
1430 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1431
1432                                                 mjpeg_y = temp_frame->get_y();
1433                                                 mjpeg_u = temp_frame->get_u();
1434                                                 mjpeg_v = temp_frame->get_v();
1435                                         }
1436
1437
1438
1439
1440                                         next_frame_lock->unlock();
1441                                         next_frame_done->lock("FileMPEG::write_frames");
1442                                         if(mjpeg_error) result = 1;
1443                                 }
1444
1445
1446
1447
1448
1449                         }
1450                 }
1451         }
1452
1453
1454
1455         return result;
1456 }
1457
1458 int FileMPEG::zmpeg3_cmdl(int colormodel)
1459 {   
1460         switch( colormodel ) {
1461         case BC_BGR888:       return zmpeg3_t::cmdl_BGR888;
1462         case BC_BGR8888:      return zmpeg3_t::cmdl_BGRA8888;
1463         case BC_RGB565:       return zmpeg3_t::cmdl_RGB565;
1464         case BC_RGB888:       return zmpeg3_t::cmdl_RGB888;
1465         case BC_RGBA8888:     return zmpeg3_t::cmdl_RGBA8888;
1466         case BC_RGBA16161616: return zmpeg3_t::cmdl_RGBA16161616;
1467         case BC_YUV420P:      return zmpeg3_t::cmdl_YUV420P;
1468         case BC_YUV422P:      return zmpeg3_t::cmdl_YUV422P;
1469         case BC_YUV422:       return zmpeg3_t::cmdl_YUYV;
1470         case BC_YUV888:       return zmpeg3_t::cmdl_YUV888;
1471         case BC_YUVA8888:     return zmpeg3_t::cmdl_YUVA8888;
1472         }
1473         return -1;
1474 }   
1475
1476 int FileMPEG::bc_colormodel(int cmdl)
1477 {
1478         switch( cmdl ) {
1479         case zmpeg3_t::cmdl_BGR888:       return BC_BGR888;
1480         case zmpeg3_t::cmdl_BGRA8888:     return BC_BGR8888;
1481         case zmpeg3_t::cmdl_RGB565:       return BC_RGB565;
1482         case zmpeg3_t::cmdl_RGB888:       return BC_RGB888;
1483         case zmpeg3_t::cmdl_RGBA8888:     return BC_RGBA8888;
1484         case zmpeg3_t::cmdl_RGBA16161616: return BC_RGBA16161616;
1485         case zmpeg3_t::cmdl_YUV420P:      return BC_YUV420P;
1486         case zmpeg3_t::cmdl_YUV422P:      return BC_YUV422P;
1487         case zmpeg3_t::cmdl_YUYV:         return BC_YUV422;
1488         case zmpeg3_t::cmdl_YUV888:       return BC_YUV888;
1489         case zmpeg3_t::cmdl_YUVA8888:     return BC_YUVA8888;
1490         }
1491         return -1;
1492 }
1493
1494 const char *FileMPEG::zmpeg3_cmdl_name(int cmdl)
1495 {
1496 # define CMDL(nm) #nm
1497   static const char *cmdl_name[] = {
1498     CMDL(BGR888),
1499     CMDL(BGRA8888),
1500     CMDL(RGB565),
1501     CMDL(RGB888),
1502     CMDL(RGBA8888),
1503     CMDL(RGBA16161616),
1504     CMDL(UNKNOWN),
1505     CMDL(601_BGR888),
1506     CMDL(601_BGRA8888),
1507     CMDL(601_RGB888),
1508     CMDL(601_RGBA8888),
1509     CMDL(601_RGB565),
1510     CMDL(YUV420P),
1511     CMDL(YUV422P),
1512     CMDL(601_YUV420P),
1513     CMDL(601_YUV422P),
1514     CMDL(UYVY),
1515     CMDL(YUYV),
1516     CMDL(601_UYVY),
1517     CMDL(601_YUYV),
1518     CMDL(YUV888),
1519     CMDL(YUVA8888),
1520     CMDL(601_YUV888),
1521     CMDL(601_YUVA8888),
1522   };
1523   return cmdl>=0 && cmdl<lengthof(cmdl_name) ? cmdl_name[cmdl] : cmdl_name[6];
1524 }
1525
1526
1527 int FileMPEG::read_frame(VFrame *frame)
1528 {
1529         if(!fd) return 1;
1530         int result = 0;
1531         int width = mpeg3_video_width(fd,file->current_layer);
1532         int height = mpeg3_video_height(fd,file->current_layer);
1533         int stream_cmdl = mpeg3_colormodel(fd,file->current_layer);
1534         int stream_color_model = bc_colormodel(stream_cmdl);
1535         int frame_color_model = frame->get_color_model();
1536         int frame_cmdl = zmpeg3_cmdl(frame_color_model);
1537         mpeg3_show_subtitle(fd, file->current_layer, file->playback_subtitle);
1538
1539
1540         switch( frame_color_model ) { // check for direct copy
1541         case BC_YUV420P:
1542         case BC_YUV422P:
1543                 if( stream_color_model == frame_color_model &&
1544                         width == frame->get_w() && height == frame->get_h() ) {
1545                         mpeg3_read_yuvframe(fd,
1546                                 (char*)frame->get_y(),
1547                                 (char*)frame->get_u(),
1548                                 (char*)frame->get_v(),
1549                                 0, 0, width, height,
1550                                 file->current_layer);
1551                         return result;
1552                 }
1553         }
1554
1555         if( frame_cmdl >= 0 ) {        // supported by read_frame
1556                 // cant rely on frame->get_rows(), format may not support it
1557                 int uvs = 0;
1558                 switch( frame_color_model ) {
1559                 case BC_YUV420P: uvs = 2;  break;
1560                 case BC_YUV422P: uvs = 1;  break;
1561                 }
1562                 //int w = frame->get_w();
1563                 int h = frame->get_h();
1564                 int bpl = frame->get_bytes_per_line();
1565                 int uvw = !uvs ? 0 : bpl / 2;
1566                 int uvh = !uvs ? 0 : h / uvs;
1567                 uint8_t *rows[h + 2*uvh], *rp;
1568                 int n = 0;
1569                 if( (rp=frame->get_y()) ) {
1570                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1571                         rp = frame->get_u();
1572                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1573                         rp = frame->get_v();
1574                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1575                 }
1576                 else {
1577                         rp = frame->get_data();  uvh *= 2;
1578                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1579                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1580                 }
1581
1582                 mpeg3_read_frame(fd, 
1583                                 rows,                /* start of each output row */
1584                                 0, 0, width, height, /* input box */
1585                                 frame->get_w(),      /* Dimensions of output_rows */
1586                                 frame->get_h(), 
1587                                 frame_cmdl,
1588                                 file->current_layer);
1589                 return result;
1590         }
1591
1592         char *y, *u, *v;
1593         mpeg3_read_yuvframe_ptr(fd, &y, &u, &v, file->current_layer);
1594         if( y && u && v ) {
1595                 BC_CModels::transfer(frame->get_rows(), 0,
1596                         frame->get_y(),
1597                         frame->get_u(),
1598                         frame->get_v(),
1599                         (unsigned char*)y,
1600                         (unsigned char*)u,
1601                         (unsigned char*)v,
1602                         0, 0, width, height,
1603                         0, 0, frame->get_w(), frame->get_h(),
1604                         stream_color_model, 
1605                         frame_color_model,
1606                         0, 
1607                         width,
1608                         frame->get_w());
1609         }
1610
1611         return result;
1612 }
1613
1614
1615 void FileMPEG::to_streamchannel(int channel, int &stream_out, int &channel_out)
1616 {
1617         int total_astreams = mpeg3_total_astreams(fd);
1618         for(stream_out = 0; stream_out < total_astreams; ++stream_out )
1619         {
1620                 int stream_channels = mpeg3_audio_channels(fd, stream_out);
1621                 if( channel < stream_channels ) break;
1622                 channel -= stream_channels;
1623         }
1624         channel_out = channel;
1625 }
1626
1627 int FileMPEG::read_samples(double *buffer, int64_t len)
1628 {
1629         if(!fd) return 0;
1630         if(len < 0) return 0;
1631
1632 // Translate pure channel to a stream and a channel in the mpeg stream
1633         int stream, channel;
1634         to_streamchannel(file->current_channel, stream, channel);
1635
1636 //printf("FileMPEG::read_samples 1 current_sample=" _LD " len=" _LD " channel=%d\n", file->current_sample, len, channel);
1637
1638         mpeg3_set_sample(fd, 
1639                 file->current_sample,
1640                 stream);
1641         mpeg3_read_audio_d(fd, 
1642                 buffer, /* Pointer to pre-allocated buffer of doubles */
1643                 channel,          /* Channel to decode */
1644                 len,         /* Number of samples to decode */
1645                 stream);          /* Stream containing the channel */
1646
1647 //      last_sample = file->current_sample;
1648         return 0;
1649 }
1650
1651
1652
1653
1654
1655
1656 FileMPEGVideo::FileMPEGVideo(FileMPEG *file)
1657  : Thread(1, 0, 0)
1658 {
1659         this->file = file;
1660         
1661         
1662         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1663         {
1664                 mpeg2enc_init_buffers();
1665                 mpeg2enc_set_w(file->asset->width);
1666                 mpeg2enc_set_h(file->asset->height);
1667                 mpeg2enc_set_rate(file->asset->frame_rate);
1668         }
1669 }
1670
1671 FileMPEGVideo::~FileMPEGVideo()
1672 {
1673         Thread::join();
1674 }
1675
1676 void FileMPEGVideo::run()
1677 {
1678         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1679         {
1680                 printf("FileMPEGVideo::run ");
1681                 for(int i = 0; i < file->vcommand_line.total; i++)
1682                 printf("%s ", file->vcommand_line.values[i]);
1683                 printf("\n");
1684                 mpeg2enc(file->vcommand_line.total, file->vcommand_line.values);
1685         }
1686         else
1687         {
1688                 while(1)
1689                 {
1690 //printf("FileMPEGVideo::run %d\n", __LINE__);
1691                         file->next_frame_lock->lock("FileMPEGVideo::run");
1692 //printf("FileMPEGVideo::run %d\n", __LINE__);
1693                         if(file->mjpeg_eof) 
1694                         {
1695                                 file->next_frame_done->unlock();
1696                                 break;
1697                         }
1698
1699
1700
1701 //printf("FileMPEGVideo::run %d\n", __LINE__);
1702 // YUV4 sequence header
1703                         if(!file->wrote_header)
1704                         {
1705                                 file->wrote_header = 1;
1706
1707                                 char interlace_string[BCTEXTLEN];
1708                                 if(!file->asset->vmpeg_progressive)
1709                                 {
1710                                         sprintf(interlace_string, file->asset->vmpeg_field_order ? "b" : "t");
1711                                 }
1712                                 else
1713                                 {
1714                                         sprintf(interlace_string, "p");
1715                                 }
1716                                 double aspect_ratio = file->asset->aspect_ratio >= 0 ?
1717                                         file->asset->aspect_ratio : 1.0;
1718 //printf("FileMPEGVideo::run %d\n", __LINE__);
1719                                 fprintf(file->mjpeg_out, "YUV4MPEG2 W%d H%d F%d:%d I%s A%d:%d C%s\n",
1720                                         file->asset->width, file->asset->height,
1721                                         (int)(file->asset->frame_rate * 1001),
1722                                         1001, interlace_string,
1723                                         (int)(aspect_ratio * 1000), 1000,
1724                                         "420mpeg2");
1725 //printf("FileMPEGVideo::run %d\n", __LINE__);
1726                         }
1727
1728 // YUV4 frame header
1729 //printf("FileMPEGVideo::run %d\n", __LINE__);
1730                         fprintf(file->mjpeg_out, "FRAME\n");
1731
1732 // YUV data
1733 //printf("FileMPEGVideo::run %d\n", __LINE__);
1734                         if(!fwrite(file->mjpeg_y, file->asset->width * file->asset->height, 1, file->mjpeg_out))
1735                                 file->mjpeg_error = 1;
1736 //printf("FileMPEGVideo::run %d\n", __LINE__);
1737                         if(!fwrite(file->mjpeg_u, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1738                                 file->mjpeg_error = 1;
1739 //printf("FileMPEGVideo::run %d\n", __LINE__);
1740                         if(!fwrite(file->mjpeg_v, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1741                                 file->mjpeg_error = 1;
1742 //printf("FileMPEGVideo::run %d\n", __LINE__);
1743                         fflush(file->mjpeg_out);
1744
1745 //printf("FileMPEGVideo::run %d\n", __LINE__);
1746                         file->next_frame_done->unlock();
1747 //printf("FileMPEGVideo::run %d\n", __LINE__);
1748                 }
1749                 pclose(file->mjpeg_out);
1750                 file->mjpeg_out = 0;
1751         }
1752 }
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765 MPEGConfigAudio::MPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
1766  : BC_Window(_(PROGRAM_NAME ": Audio Compression"),
1767         parent_window->get_abs_cursor_x(1),
1768         parent_window->get_abs_cursor_y(1),
1769         310,
1770         120,
1771         -1,
1772         -1,
1773         0,
1774         0,
1775         1)
1776 {
1777         this->parent_window = parent_window;
1778         this->asset = asset;
1779 }
1780
1781 MPEGConfigAudio::~MPEGConfigAudio()
1782 {
1783 }
1784
1785 void MPEGConfigAudio::create_objects()
1786 {
1787         int x = 10, y = 10;
1788         int x1 = 150;
1789         MPEGLayer *layer;
1790
1791         lock_window("MPEGConfigAudio::create_objects");
1792         if(asset->format == FILE_MPEG)
1793         {
1794                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1795                 unlock_window();
1796                 return;
1797         }
1798
1799
1800         add_tool(new BC_Title(x, y, _("Layer:")));
1801         add_tool(layer = new MPEGLayer(x1, y, this));
1802         layer->create_objects();
1803
1804         y += 30;
1805         add_tool(new BC_Title(x, y, _("Kbits per second:")));
1806         add_tool(bitrate = new MPEGABitrate(x1, y, this));
1807         bitrate->create_objects();
1808         
1809         
1810         add_subwindow(new BC_OKButton(this));
1811         show_window(1);
1812         unlock_window();
1813 }
1814
1815 int MPEGConfigAudio::close_event()
1816 {
1817         set_done(0);
1818         return 1;
1819 }
1820
1821
1822
1823
1824
1825
1826
1827 MPEGLayer::MPEGLayer(int x, int y, MPEGConfigAudio *gui)
1828  : BC_PopupMenu(x, y, 100, layer_to_string(gui->asset->ampeg_derivative))
1829 {
1830         this->gui = gui;
1831 }
1832
1833 void MPEGLayer::create_objects()
1834 {
1835         add_item(new BC_MenuItem(layer_to_string(2)));
1836         add_item(new BC_MenuItem(layer_to_string(3)));
1837 }
1838
1839 int MPEGLayer::handle_event()
1840 {
1841         gui->asset->ampeg_derivative = string_to_layer(get_text());
1842         gui->bitrate->set_layer(gui->asset->ampeg_derivative);
1843         return 1;
1844 };
1845
1846 int MPEGLayer::string_to_layer(char *string)
1847 {
1848         if(!strcasecmp(layer_to_string(2), string))
1849                 return 2;
1850         if(!strcasecmp(layer_to_string(3), string))
1851                 return 3;
1852
1853         return 2;
1854 }
1855
1856 char* MPEGLayer::layer_to_string(int layer)
1857 {
1858         switch(layer)
1859         {
1860                 case 2:
1861                         return _("II");
1862                         break;
1863                 
1864                 case 3:
1865                         return _("III");
1866                         break;
1867                         
1868                 default:
1869                         return _("II");
1870                         break;
1871         }
1872 }
1873
1874
1875
1876
1877
1878
1879
1880 MPEGABitrate::MPEGABitrate(int x, int y, MPEGConfigAudio *gui)
1881  : BC_PopupMenu(x, 
1882         y, 
1883         100, 
1884         bitrate_to_string(gui->string, gui->asset->ampeg_bitrate))
1885 {
1886         this->gui = gui;
1887 }
1888
1889 void MPEGABitrate::create_objects()
1890 {
1891         set_layer(gui->asset->ampeg_derivative);
1892 }
1893
1894 void MPEGABitrate::set_layer(int layer)
1895 {
1896         while(total_items())
1897         {
1898                 remove_item(0);
1899         }
1900
1901         if(layer == 2)
1902         {
1903                 add_item(new BC_MenuItem("160"));
1904                 add_item(new BC_MenuItem("192"));
1905                 add_item(new BC_MenuItem("224"));
1906                 add_item(new BC_MenuItem("256"));
1907                 add_item(new BC_MenuItem("320"));
1908                 add_item(new BC_MenuItem("384"));
1909         }
1910         else
1911         {
1912                 add_item(new BC_MenuItem("8"));
1913                 add_item(new BC_MenuItem("16"));
1914                 add_item(new BC_MenuItem("24"));
1915                 add_item(new BC_MenuItem("32"));
1916                 add_item(new BC_MenuItem("40"));
1917                 add_item(new BC_MenuItem("48"));
1918                 add_item(new BC_MenuItem("56"));
1919                 add_item(new BC_MenuItem("64"));
1920                 add_item(new BC_MenuItem("80"));
1921                 add_item(new BC_MenuItem("96"));
1922                 add_item(new BC_MenuItem("112"));
1923                 add_item(new BC_MenuItem("128"));
1924                 add_item(new BC_MenuItem("144"));
1925                 add_item(new BC_MenuItem("160"));
1926                 add_item(new BC_MenuItem("192"));
1927                 add_item(new BC_MenuItem("224"));
1928                 add_item(new BC_MenuItem("256"));
1929                 add_item(new BC_MenuItem("320"));
1930         }
1931 }
1932
1933 int MPEGABitrate::handle_event()
1934 {
1935         gui->asset->ampeg_bitrate = string_to_bitrate(get_text());
1936         return 1;
1937 };
1938
1939 int MPEGABitrate::string_to_bitrate(char *string)
1940 {
1941         return atol(string);
1942 }
1943
1944
1945 char* MPEGABitrate::bitrate_to_string(char *string, int bitrate)
1946 {
1947         sprintf(string, "%d", bitrate);
1948         return string;
1949 }
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959 MPEGConfigVideo::MPEGConfigVideo(BC_WindowBase *parent_window, 
1960         Asset *asset)
1961  : BC_Window(_(PROGRAM_NAME ": Video Compression"),
1962         parent_window->get_abs_cursor_x(1),
1963         parent_window->get_abs_cursor_y(1),
1964         500,
1965         400,
1966         -1,
1967         -1,
1968         0,
1969         0,
1970         1)
1971 {
1972         this->parent_window = parent_window;
1973         this->asset = asset;
1974         reset_cmodel();
1975 }
1976
1977 MPEGConfigVideo::~MPEGConfigVideo()
1978 {
1979 }
1980
1981 void MPEGConfigVideo::create_objects()
1982 {
1983         int x = 10, y = 10;
1984         int x1 = x + 150;
1985         //int x2 = x + 300;
1986
1987         lock_window("MPEGConfigVideo::create_objects");
1988         if(asset->format == FILE_MPEG)
1989         {
1990                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1991                 unlock_window();
1992                 return;
1993         }
1994
1995         add_subwindow(new BC_Title(x, y, _("Color model:")));
1996         add_subwindow(cmodel = new MPEGColorModel(x1, y, this));
1997         cmodel->create_objects();
1998         y += 30;
1999
2000         update_cmodel_objs();
2001
2002         add_subwindow(new BC_OKButton(this));
2003         show_window(1);
2004         unlock_window();
2005 }
2006
2007 int MPEGConfigVideo::close_event()
2008 {
2009         set_done(0);
2010         return 1;
2011 }
2012
2013
2014 void MPEGConfigVideo::delete_cmodel_objs()
2015 {
2016         delete preset;
2017         delete derivative;
2018         delete bitrate;
2019         delete fixed_bitrate;
2020         delete quant;
2021         delete fixed_quant;
2022         delete iframe_distance;
2023         delete pframe_distance;
2024         delete top_field_first;
2025         delete progressive;
2026         delete denoise;
2027         delete seq_codes;
2028         titles.remove_all_objects();
2029         reset_cmodel();
2030 }
2031
2032 void MPEGConfigVideo::reset_cmodel()
2033 {
2034         preset = 0;
2035         derivative = 0;
2036         bitrate = 0;
2037         fixed_bitrate = 0;
2038         quant = 0;
2039         fixed_quant = 0;
2040         iframe_distance = 0;
2041         pframe_distance = 0;
2042         top_field_first = 0;
2043         progressive = 0;
2044         denoise = 0;
2045         seq_codes = 0;
2046 }
2047
2048 void MPEGConfigVideo::update_cmodel_objs()
2049 {
2050         BC_Title *title;
2051         int x = 10;
2052         int y = 40;
2053         int x1 = x + 150;
2054         int x2 = x + 280;
2055
2056         delete_cmodel_objs();
2057
2058         if(asset->vmpeg_cmodel == BC_YUV420P)
2059         {
2060                 add_subwindow(title = new BC_Title(x, y + 5, _("Format Preset:")));
2061                 titles.append(title);
2062                 add_subwindow(preset = new MPEGPreset(x1, y, this));
2063                 preset->create_objects();
2064                 y += 30;
2065         }
2066
2067         add_subwindow(title = new BC_Title(x, y + 5, _("Derivative:")));
2068         titles.append(title);
2069         add_subwindow(derivative = new MPEGDerivative(x1, y, this));
2070         derivative->create_objects();
2071         y += 30;
2072
2073         add_subwindow(title = new BC_Title(x, y + 5, _("Bitrate:")));
2074         titles.append(title);
2075         add_subwindow(bitrate = new MPEGBitrate(x1, y, this));
2076         add_subwindow(fixed_bitrate = new MPEGFixedBitrate(x2, y, this));
2077         y += 30;
2078
2079         add_subwindow(title = new BC_Title(x, y, _("Quantization:")));
2080         titles.append(title);
2081         quant = new MPEGQuant(x1, y, this);
2082         quant->create_objects();
2083         add_subwindow(fixed_quant = new MPEGFixedQuant(x2, y, this));
2084         y += 30;
2085
2086         add_subwindow(title = new BC_Title(x, y, _("I frame distance:")));
2087         titles.append(title);
2088         iframe_distance = new MPEGIFrameDistance(x1, y, this);
2089         iframe_distance->create_objects();
2090         y += 30;
2091
2092         if(asset->vmpeg_cmodel == BC_YUV420P)
2093         {
2094                 add_subwindow(title = new BC_Title(x, y, _("P frame distance:")));
2095                 titles.append(title);
2096                 pframe_distance = new MPEGPFrameDistance(x1, y, this);
2097                 pframe_distance->create_objects();
2098                 y += 30;
2099
2100                 add_subwindow(top_field_first = new BC_CheckBox(x, y, &asset->vmpeg_field_order, _("Bottom field first")));
2101                 y += 30;
2102         }
2103
2104         add_subwindow(progressive = new BC_CheckBox(x, y, &asset->vmpeg_progressive, _("Progressive frames")));
2105         y += 30;
2106         add_subwindow(denoise = new BC_CheckBox(x, y, &asset->vmpeg_denoise, _("Denoise")));
2107         y += 30;
2108         add_subwindow(seq_codes = new BC_CheckBox(x, y, &asset->vmpeg_seq_codes, _("Sequence start codes in every GOP")));
2109
2110 }
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124 MPEGDerivative::MPEGDerivative(int x, int y, MPEGConfigVideo *gui)
2125  : BC_PopupMenu(x, y, 150, derivative_to_string(gui->asset->vmpeg_derivative))
2126 {
2127         this->gui = gui;
2128 }
2129
2130 void MPEGDerivative::create_objects()
2131 {
2132         add_item(new BC_MenuItem(derivative_to_string(1)));
2133         add_item(new BC_MenuItem(derivative_to_string(2)));
2134 }
2135
2136 int MPEGDerivative::handle_event()
2137 {
2138         gui->asset->vmpeg_derivative = string_to_derivative(get_text());
2139         return 1;
2140 };
2141
2142 int MPEGDerivative::string_to_derivative(char *string)
2143 {
2144         if(!strcasecmp(derivative_to_string(1), string))
2145                 return 1;
2146         if(!strcasecmp(derivative_to_string(2), string))
2147                 return 2;
2148
2149         return 1;
2150 }
2151
2152 char* MPEGDerivative::derivative_to_string(int derivative)
2153 {
2154         switch(derivative)
2155         {
2156                 case 1:
2157                         return _("MPEG-1");
2158                         break;
2159                 
2160                 case 2:
2161                         return _("MPEG-2");
2162                         break;
2163                         
2164                 default:
2165                         return _("MPEG-1");
2166                         break;
2167         }
2168 }
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180 MPEGPreset::MPEGPreset(int x, int y, MPEGConfigVideo *gui)
2181  : BC_PopupMenu(x, y, 200, value_to_string(gui->asset->vmpeg_preset))
2182 {
2183         this->gui = gui;
2184 }
2185
2186 void MPEGPreset::create_objects()
2187 {
2188         for(int i = 0; i < 10; i++)
2189         {
2190                 add_item(new BC_MenuItem(value_to_string(i)));
2191         }
2192 }
2193
2194 int MPEGPreset::handle_event()
2195 {
2196         gui->asset->vmpeg_preset = string_to_value(get_text());
2197         return 1;
2198 }
2199
2200 int MPEGPreset::string_to_value(char *string)
2201 {
2202         for(int i = 0; i < 10; i++)
2203         {
2204                 if(!strcasecmp(value_to_string(i), string))
2205                         return i;
2206         }
2207         return 0;
2208 }
2209
2210 char* MPEGPreset::value_to_string(int derivative)
2211 {
2212         switch(derivative)
2213         {
2214                 case 0: return _("Generic MPEG-1"); break;
2215                 case 1: return _("standard VCD"); break;
2216                 case 2: return _("user VCD"); break;
2217                 case 3: return _("Generic MPEG-2"); break;
2218                 case 4: return _("standard SVCD"); break;
2219                 case 5: return _("user SVCD"); break;
2220                 case 6: return _("VCD Still sequence"); break;
2221                 case 7: return _("SVCD Still sequence"); break;
2222                 case 8: return _("DVD NAV"); break;
2223                 case 9: return _("DVD"); break;
2224                 default: return _("Generic MPEG-1"); break;
2225         }
2226 }
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238 MPEGBitrate::MPEGBitrate(int x, int y, MPEGConfigVideo *gui)
2239  : BC_TextBox(x, y, 100, 1, gui->asset->vmpeg_bitrate)
2240 {
2241         this->gui = gui;
2242 }
2243
2244
2245 int MPEGBitrate::handle_event()
2246 {
2247         gui->asset->vmpeg_bitrate = atol(get_text());
2248         return 1;
2249 };
2250
2251
2252
2253
2254
2255 MPEGQuant::MPEGQuant(int x, int y, MPEGConfigVideo *gui)
2256  : BC_TumbleTextBox(gui, 
2257         (int64_t)gui->asset->vmpeg_quantization, 
2258         (int64_t)1,
2259         (int64_t)100,
2260         x, 
2261         y,
2262         100)
2263 {
2264         this->gui = gui;
2265 }
2266
2267 int MPEGQuant::handle_event()
2268 {
2269         gui->asset->vmpeg_quantization = atol(get_text());
2270         return 1;
2271 };
2272
2273 MPEGFixedBitrate::MPEGFixedBitrate(int x, int y, MPEGConfigVideo *gui)
2274  : BC_Radial(x, y, gui->asset->vmpeg_fix_bitrate, _("Fixed bitrate"))
2275 {
2276         this->gui = gui;
2277 }
2278
2279 int MPEGFixedBitrate::handle_event()
2280 {
2281         update(1);
2282         gui->asset->vmpeg_fix_bitrate = 1;
2283         gui->fixed_quant->update(0);
2284         return 1;
2285 };
2286
2287 MPEGFixedQuant::MPEGFixedQuant(int x, int y, MPEGConfigVideo *gui)
2288  : BC_Radial(x, y, !gui->asset->vmpeg_fix_bitrate, _("Fixed quantization"))
2289 {
2290         this->gui = gui;
2291 }
2292
2293 int MPEGFixedQuant::handle_event()
2294 {
2295         update(1);
2296         gui->asset->vmpeg_fix_bitrate = 0;
2297         gui->fixed_bitrate->update(0);
2298         return 1;
2299 };
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309 MPEGIFrameDistance::MPEGIFrameDistance(int x, int y, MPEGConfigVideo *gui)
2310  : BC_TumbleTextBox(gui, 
2311         (int64_t)gui->asset->vmpeg_iframe_distance, 
2312         (int64_t)1,
2313         (int64_t)100,
2314         x, 
2315         y,
2316         50)
2317 {
2318         this->gui = gui;
2319 }
2320
2321 int MPEGIFrameDistance::handle_event()
2322 {
2323         gui->asset->vmpeg_iframe_distance = atoi(get_text());
2324         return 1;
2325 }
2326
2327
2328
2329
2330
2331
2332
2333 MPEGPFrameDistance::MPEGPFrameDistance(int x, int y, MPEGConfigVideo *gui)
2334  : BC_TumbleTextBox(gui, 
2335         (int64_t)gui->asset->vmpeg_pframe_distance, 
2336         (int64_t)0,
2337         (int64_t)2,
2338         x, 
2339         y,
2340         50)
2341 {
2342         this->gui = gui;
2343 }
2344
2345 int MPEGPFrameDistance::handle_event()
2346 {
2347         gui->asset->vmpeg_pframe_distance = atoi(get_text());
2348         return 1;
2349 }
2350
2351
2352
2353
2354
2355
2356
2357
2358 MPEGColorModel::MPEGColorModel(int x, int y, MPEGConfigVideo *gui)
2359  : BC_PopupMenu(x, y, 150, cmodel_to_string(gui->asset->vmpeg_cmodel))
2360 {
2361         this->gui = gui;
2362 }
2363
2364 void MPEGColorModel::create_objects()
2365 {
2366         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV420P)));
2367         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV422P)));
2368 }
2369
2370 int MPEGColorModel::handle_event()
2371 {
2372         gui->asset->vmpeg_cmodel = string_to_cmodel(get_text());
2373         gui->update_cmodel_objs();
2374         gui->show_window(1);
2375         return 1;
2376 };
2377
2378 int MPEGColorModel::string_to_cmodel(char *string)
2379 {
2380         if(!strcasecmp(cmodel_to_string(BC_YUV420P), string))
2381                 return BC_YUV420P;
2382         if(!strcasecmp(cmodel_to_string(BC_YUV422P), string))
2383                 return BC_YUV422P;
2384         return BC_YUV420P;
2385 }
2386
2387 char* MPEGColorModel::cmodel_to_string(int cmodel)
2388 {
2389         switch(cmodel)
2390         {
2391                 case BC_YUV420P: return _("YUV 4:2:0");
2392                 case BC_YUV422P: return _("YUV 4:2:2");
2393                 default: return _("YUV 4:2:0");
2394         }
2395 }
2396
2397
2398
2399
2400
2401