summaryrefslogtreecommitdiffstats
path: root/libk3b/projects/mixedcd/k3bmixedjob.cpp
blob: 53d930baf7d1192f875ae875a7132dc38214c0e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
/*
 *
 * $Id: k3bmixedjob.cpp 690212 2007-07-20 11:02:13Z trueg $
 * Copyright (C) 2003 Sebastian Trueg <trueg@k3b.org>
 *
 * This file is part of the K3b project.
 * Copyright (C) 1998-2007 Sebastian Trueg <trueg@k3b.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * See the file "COPYING" for the exact licensing terms.
 */




#include "k3bmixedjob.h"
#include "k3bmixeddoc.h"

#include <k3bdatadoc.h>
#include <k3bisoimager.h>
#include <k3bmsinfofetcher.h>
#include <k3baudioimager.h>
#include <k3baudiodoc.h>
#include <k3baudiotrack.h>
#include <k3baudionormalizejob.h>
#include <k3baudiojobtempdata.h>
#include <k3baudiomaxspeedjob.h>
#include <k3bdevicemanager.h>
#include <k3bdevice.h>
#include <k3bdevicehandler.h>
#include <k3bmsf.h>
#include <k3bglobals.h>
#include <k3bexternalbinmanager.h>
#include <k3bversion.h>
#include <k3bcore.h>
#include <k3bcdrecordwriter.h>
#include <k3bcdrdaowriter.h>
#include <k3btocfilewriter.h>
#include <k3binffilewriter.h>
#include <k3bglobalsettings.h>
#include <k3baudiofile.h>

#include <tqfile.h>
#include <tqdatastream.h>
#include <tqapplication.h>

#include <kdebug.h>
#include <klocale.h>
#include <ktempfile.h>
#include <kio/netaccess.h>
#include <kio/global.h>
#include <kstringhandler.h>


static TQString createNonExistingFilesString( const TQValueList<K3bAudioFile*>& items, unsigned int max )
{
  TQString s;
  unsigned int cnt = 0;
  for( TQValueList<K3bAudioFile*>::const_iterator it = items.begin();
       it != items.end(); ++it ) {

    s += KStringHandler::csqueeze( (*it)->filename(), 60 );

    ++cnt;
    if( cnt >= max || it == items.end() )
      break;

    s += "<br>";
  }

  if( items.count() > max )
    s += "...";

  return s;
}



class K3bMixedJob::Private
{
public:
  Private()
    : maxSpeedJob(0) {
  }


  int copies;
  int copiesDone;

  K3bAudioMaxSpeedJob* maxSpeedJob;
  bool maxSpeed;
};


K3bMixedJob::K3bMixedJob( K3bMixedDoc* doc, K3bJobHandler* hdl, TQObject* parent )
  : K3bBurnJob( hdl, parent ),
    m_doc( doc ),
    m_normalizeJob(0)
{
  d = new Private;

  m_isoImager = new K3bIsoImager( doc->dataDoc(), this, this );
  connect( m_isoImager, TQT_SIGNAL(infoMessage(const TQString&, int)), this, TQT_SIGNAL(infoMessage(const TQString&, int)) );
  connect( m_isoImager, TQT_SIGNAL(percent(int)), this, TQT_SLOT(slotIsoImagerPercent(int)) );
  connect( m_isoImager, TQT_SIGNAL(finished(bool)), this, TQT_SLOT(slotIsoImagerFinished(bool)) );
  connect( m_isoImager, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)),
	   this, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)) );

  m_audioImager = new K3bAudioImager( doc->audioDoc(), this, this );
  connect( m_audioImager, TQT_SIGNAL(infoMessage(const TQString&, int)),
	   this, TQT_SIGNAL(infoMessage(const TQString&, int)) );
  connect( m_audioImager, TQT_SIGNAL(percent(int)), this, TQT_SLOT(slotAudioDecoderPercent(int)) );
  connect( m_audioImager, TQT_SIGNAL(subPercent(int)), this, TQT_SLOT(slotAudioDecoderSubPercent(int)) );
  connect( m_audioImager, TQT_SIGNAL(finished(bool)), this, TQT_SLOT(slotAudioDecoderFinished(bool)) );
  connect( m_audioImager, TQT_SIGNAL(nextTrack(int, int)), this, TQT_SLOT(slotAudioDecoderNextTrack(int, int)) );

  m_msInfoFetcher = new K3bMsInfoFetcher( this, this );
  connect( m_msInfoFetcher, TQT_SIGNAL(finished(bool)), this, TQT_SLOT(slotMsInfoFetched(bool)) );
  connect( m_msInfoFetcher, TQT_SIGNAL(infoMessage(const TQString&, int)), this, TQT_SIGNAL(infoMessage(const TQString&, int)) );

  m_writer = 0;
  m_tocFile = 0;
  m_tempData = new K3bAudioJobTempData( m_doc->audioDoc(), this );
}


K3bMixedJob::~K3bMixedJob()
{
  delete m_tocFile;
  delete d;
}


K3bDevice::Device* K3bMixedJob::writer() const
{
  if( m_doc->onlyCreateImages() )
    return 0;
  else
    return m_doc->burner();
}


K3bDoc* K3bMixedJob::doc() const
{
  return m_doc;
}


void K3bMixedJob::start()
{
  jobStarted();

  m_canceled = false;
  m_errorOccuredAndAlreadyReported = false;
  d->copiesDone = 0;
  d->copies = m_doc->copies();
  m_currentAction = PREPARING_DATA;
  d->maxSpeed = false;

  if( m_doc->dummy() )
    d->copies = 1;

  prepareProgressInformation();

  //
  // Check if all files exist
  //
  TQValueList<K3bAudioFile*> nonExistingFiles;
  K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
  while( track ) {
    K3bAudioDataSource* source = track->firstSource();
    while( source ) {
      if( K3bAudioFile* file = dynamic_cast<K3bAudioFile*>( source ) ) {
	if( !TQFile::exists( file->filename() ) )
	  nonExistingFiles.append( file );
      }
      source = source->next();
    }
    track = track->next();
  }
  if( !nonExistingFiles.isEmpty() ) {
    if( questionYesNo( "<p>" + i18n("The following files could not be found. Do you want to remove them from the "
				    "project and continue without adding them to the image?") +
		       "<p>" + createNonExistingFilesString( nonExistingFiles, 10 ),
		       i18n("Warning"),
		       i18n("Remove missing files and continue"),
		       i18n("Cancel and go back") ) ) {
      for( TQValueList<K3bAudioFile*>::const_iterator it = nonExistingFiles.begin();
	   it != nonExistingFiles.end(); ++it ) {
	delete *it;
      }
    }
    else {
      m_canceled = true;
      emit canceled();
      jobFinished(false);
      return;
    }
  }

  //
  // Make sure the project is not empty
  //
  if( m_doc->audioDoc()->numOfTracks() == 0 ) {
    emit infoMessage( i18n("Please add files to your project first."), ERROR );
    jobFinished(false);
    return;
  }


  // set some flags that are needed
  m_doc->audioDoc()->setOnTheFly( m_doc->onTheFly() );  // for the toc writer
  m_doc->audioDoc()->setHideFirstTrack( false );   // unsupported
  m_doc->dataDoc()->setBurner( m_doc->burner() );  // so the isoImager can read ms data

  emit newTask( i18n("Preparing data") );

  determineWritingMode();

  //
  // First we make sure the data portion is valid
  //

  // we do not have msinfo yet
  m_currentAction = INITIALIZING_IMAGER;
  m_isoImager->setMultiSessionInfo( TQString() );
  m_isoImager->init();
}


void K3bMixedJob::startFirstCopy()
{
  //
  // if not onthefly create the iso image and then the wavs
  // and write then
  // if onthefly calculate the iso size
  //
  if( m_doc->onTheFly() ) {
    if( m_doc->speed() == 0 ) {
      emit newSubTask( i18n("Determining maximum writing speed") );

      //
      // try to determine the max possible speed
      // no need to check the data track's max speed. Most current systems are able
      // to handle the maxium possible
      //
      if( !d->maxSpeedJob ) {
	// the maxspeed job gets the device from the doc:
	m_doc->audioDoc()->setBurner( m_doc->burner() );
	d->maxSpeedJob = new K3bAudioMaxSpeedJob( m_doc->audioDoc(), this, this );
	connect( d->maxSpeedJob, TQT_SIGNAL(percent(int)),
		 this, TQT_SIGNAL(subPercent(int)) );
	connect( d->maxSpeedJob, TQT_SIGNAL(finished(bool)),
		 this, TQT_SLOT(slotMaxSpeedJobFinished(bool)) );
      }
      d->maxSpeedJob->start();
    }
    else if( m_doc->mixedType() != K3bMixedDoc::DATA_SECOND_SESSION ) {
      m_currentAction = PREPARING_DATA;
      m_isoImager->calculateSize();
    }
    else {
      // we cannot calculate the size since we don't have the msinfo yet
      // so first write the audio session
      writeNextCopy();
    }
  }
  else {
    emit burning(false);

    emit infoMessage( i18n("Creating audio image files in %1").tqarg(m_doc->tempDir()), INFO );

    m_tempFilePrefix = K3b::findUniqueFilePrefix( ( !m_doc->audioDoc()->title().isEmpty()
						    ? m_doc->audioDoc()->title()
						    : m_doc->dataDoc()->isoOptions().volumeID() ),
						  m_doc->tempDir() );

    m_tempData->prepareTempFileNames( m_doc->tempDir() );
    TQStringList filenames;
    for( K3bAudioTrack* track = m_doc->audioDoc()->firstTrack(); track; track = track->next() )
      filenames += m_tempData->bufferFileName( track );
    m_audioImager->setImageFilenames( filenames );

    if( m_doc->mixedType() != K3bMixedDoc::DATA_SECOND_SESSION ) {
      createIsoImage();
    }
    else {
      emit newTask( i18n("Creating audio image files") );
      m_currentAction = CREATING_AUDIO_IMAGE;
      m_audioImager->start();
    }
  }
}


void K3bMixedJob::slotMaxSpeedJobFinished( bool success )
{
  d->maxSpeed = success;
  if( !success )
    emit infoMessage( i18n("Unable to determine maximum speed for some reason. Ignoring."), WARNING );

  if( m_doc->mixedType() != K3bMixedDoc::DATA_SECOND_SESSION ) {
    m_currentAction = PREPARING_DATA;
    m_isoImager->calculateSize();
  }
  else {
    // we cannot calculate the size since we don't have the msinfo yet
    // so first write the audio session
    writeNextCopy();
  }
}


void K3bMixedJob::writeNextCopy()
{
  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
    m_currentAction = WRITING_AUDIO_IMAGE;
    if( !prepareWriter() || !startWriting() ) {
      cleanupAfterError();
      jobFinished(false);
    }
    else if( m_doc->onTheFly() )
      m_audioImager->start();
  }
  else {
    // the prepareWriter method needs the action to be set
    if( m_doc->mixedType() == K3bMixedDoc::DATA_LAST_TRACK )
      m_currentAction = WRITING_AUDIO_IMAGE;
    else
      m_currentAction = WRITING_ISO_IMAGE;

    if( !prepareWriter() || !startWriting() ) {
      cleanupAfterError();
      jobFinished(false);
    }
    else if( m_doc->onTheFly() ) {
      if( m_doc->mixedType() == K3bMixedDoc::DATA_LAST_TRACK )
	m_audioImager->start();
      else
	m_isoImager->start();
    }
  }
}


void K3bMixedJob::cancel()
{
  m_canceled = true;

  if( d->maxSpeedJob )
    d->maxSpeedJob->cancel();

  if( m_writer )
    m_writer->cancel();
  m_isoImager->cancel();
  m_audioImager->cancel();
  m_msInfoFetcher->cancel();
  emit infoMessage( i18n("Writing canceled."), K3bJob::ERROR );
  removeBufferFiles();
  emit canceled();
  jobFinished(false);
}


void K3bMixedJob::slotMsInfoFetched( bool success )
{
  if( m_canceled || m_errorOccuredAndAlreadyReported )
    return;

  if( success ) {
    if( m_usedDataWritingApp == K3b::CDRECORD )
      m_isoImager->setMultiSessionInfo( m_msInfoFetcher->msInfo() );
    else  // cdrdao seems to write a 150 blocks pregap that is not used by cdrecord
      m_isoImager->setMultiSessionInfo( TQString("%1,%2")
					.tqarg(m_msInfoFetcher->lastSessionStart())
					.tqarg(m_msInfoFetcher->nextSessionStart()+150) );

    if( m_doc->onTheFly() ) {
      m_currentAction = PREPARING_DATA;
      m_isoImager->calculateSize();
    }
    else {
      createIsoImage();
    }
  }
  else {
    // the MsInfoFetcher already emitted failure info
    cleanupAfterError();
    jobFinished(false);
  }
}


void K3bMixedJob::slotIsoImagerFinished( bool success )
{
  if( m_canceled || m_errorOccuredAndAlreadyReported )
    return;

  //
  // Initializing imager before the first copy
  //
  if( m_currentAction == INITIALIZING_IMAGER ) {
    if( success ) {
      m_currentAction = PREPARING_DATA;

      // check the size
      m_projectSize  = m_isoImager->size() + m_doc->audioDoc()->length();
      if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION )
	m_projectSize += 11400; // the session gap

      startFirstCopy();
    }
    else {
      cleanupAfterError();
      jobFinished( false );
    }
  }

  //
  // Recalculated iso image size
  //
  else if( m_currentAction == PREPARING_DATA ) {
    if( success ) {
      // 1. data in first track:
      //    start isoimager and writer
      //    when isoimager finishes start audiodecoder

      // 2. data in last track
      //    start audiodecoder and writer
      //    when audiodecoder finishes start isoimager

      // 3. data in second session
      //    start audiodecoder and writer
      //    start isoimager and writer

      if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
	m_currentAction = WRITING_ISO_IMAGE;
	if( !prepareWriter() || !startWriting() ) {
	  cleanupAfterError();
	  jobFinished(false);
	}
	else
	  m_isoImager->start();
      }
      else
	writeNextCopy();
    }
    else {
      cleanupAfterError();
      jobFinished( false );
    }
  }

  //
  // Image creation finished
  //
  else {
    if( !success ) {
      emit infoMessage( i18n("Error while creating ISO image."), ERROR );
      cleanupAfterError();

      jobFinished( false );
      return;
    }

    if( m_doc->onTheFly() ) {
      if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK ) {
	m_currentAction = WRITING_AUDIO_IMAGE;
	m_audioImager->start();
      }
    }
    else {
      emit infoMessage( i18n("ISO image successfully created."), SUCCESS );

      if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
	m_currentAction = WRITING_ISO_IMAGE;

	if( !prepareWriter() || !startWriting() ) {
	  cleanupAfterError();
	  jobFinished(false);
	}
      }
      else {
	emit newTask( i18n("Creating audio image files") );
	m_currentAction = CREATING_AUDIO_IMAGE;
	m_audioImager->start();
      }
    }
  }
}


void K3bMixedJob::slotWriterFinished( bool success )
{
  if( m_canceled || m_errorOccuredAndAlreadyReported )
    return;

  if( !success ) {
    cleanupAfterError();
    jobFinished(false);
    return;
  }

  emit burning(false);

  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION && m_currentAction == WRITING_AUDIO_IMAGE ) {
    // reload the media (as a subtask so the user does not see the "Flushing cache" or "Fixating" messages while
    // doing so
    emit newSubTask( i18n("Reloading the medium") );
    connect( K3bDevice::reload( m_doc->burner() ), TQT_SIGNAL(finished(bool)),
	     this, TQT_SLOT(slotMediaReloadedForSecondSession(bool)) );
  }
  else {
    d->copiesDone++;
    if( d->copiesDone < d->copies ) {
      K3bDevice::eject( m_doc->burner() );
      writeNextCopy();
    }
    else {
      if( !m_doc->onTheFly() && m_doc->removeImages() )
	removeBufferFiles();

      if( k3bcore->globalSettings()->ejectMedia() )
          K3bDevice::eject( m_doc->burner() );

      jobFinished(true);
    }
  }
}


void K3bMixedJob::slotMediaReloadedForSecondSession( bool success )
{
  if( !success )
    blockingInformation( i18n("Please reload the medium and press 'ok'"),
			 i18n("Unable to close the tray") );

  // start the next session
  m_currentAction = WRITING_ISO_IMAGE;
  if( d->copiesDone > 0 ) {
    // we only create the image once. This should not be a problem???
    if( !prepareWriter() || !startWriting() ) {
      cleanupAfterError();
      jobFinished(false);
    }
    else if( m_doc->onTheFly() ) {
      m_isoImager->start();
    }
  }
  else if( m_doc->dummy() ) {
    // do not try to get ms info in simulation mode since the cd is empty!
    if( m_doc->onTheFly() ) {
      m_currentAction = PREPARING_DATA;
      m_isoImager->calculateSize();
    }
    else
      createIsoImage();
  }
  else {
    m_currentAction = FETCHING_MSINFO;
    m_msInfoFetcher->setDevice( m_doc->burner() );
    m_msInfoFetcher->start();
  }
}


void K3bMixedJob::slotAudioDecoderFinished( bool success )
{
  if( m_canceled || m_errorOccuredAndAlreadyReported )
    return;

  if( !success ) {
    emit infoMessage( i18n("Error while decoding audio tracks."), ERROR );
    cleanupAfterError();
    jobFinished(false);
    return;
  }

  if( m_doc->onTheFly() ) {
    if( m_doc->mixedType() == K3bMixedDoc::DATA_LAST_TRACK ) {
      m_currentAction = WRITING_ISO_IMAGE;
      m_isoImager->start();
    }
  }
  else {
    emit infoMessage( i18n("Audio images successfully created."), SUCCESS );

    if( m_doc->audioDoc()->normalize() ) {
      normalizeFiles();
    }
    else {
      if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK )
	m_currentAction = WRITING_ISO_IMAGE;
      else
	m_currentAction = WRITING_AUDIO_IMAGE;

      if( !prepareWriter() || !startWriting() ) {
	cleanupAfterError();
	jobFinished(false);
      }
    }
  }
}


void K3bMixedJob::slotAudioDecoderNextTrack( int t, int tt )
{
  if( m_doc->onlyCreateImages() || !m_doc->onTheFly() ) {
    K3bAudioTrack* track = m_doc->audioDoc()->getTrack(t);
    emit newSubTask( i18n("Decoding audio track %1 of %2%3")
		     .tqarg(t)
		     .tqarg(tt)
		     .tqarg( track->title().isEmpty() || track->artist().isEmpty()
			   ? TQString()
			   : " (" + track->artist() + " - " + track->title() + ")" ) );
  }
}


bool K3bMixedJob::prepareWriter()
{
  if( m_writer ) delete m_writer;

  if( ( m_currentAction == WRITING_ISO_IMAGE && m_usedDataWritingApp == K3b::CDRECORD ) ||
      ( m_currentAction == WRITING_AUDIO_IMAGE && m_usedAudioWritingApp == K3b::CDRECORD ) )  {

    if( !writeInfFiles() ) {
      kdDebug() << "(K3bMixedJob) could not write inf-files." << endl;
      emit infoMessage( i18n("IO Error"), ERROR );

      return false;
    }

    K3bCdrecordWriter* writer = new K3bCdrecordWriter( m_doc->burner(), this, this );

    // only write the audio tracks in DAO mode
    if( m_currentAction == WRITING_ISO_IMAGE )
      writer->setWritingMode( m_usedDataWritingMode );
    else
      writer->setWritingMode( m_usedAudioWritingMode );

    writer->setSimulate( m_doc->dummy() );
    writer->setBurnSpeed( m_doc->speed() );

    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
      if( m_currentAction == WRITING_ISO_IMAGE ) {
	if( m_doc->onTheFly() )
	  writer->addArgument("-waiti");

	addDataTrack( writer );
      }
      else {
	writer->addArgument("-multi");
	addAudioTracks( writer );
      }
    }
    else {
      if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK )
	addDataTrack( writer );
      addAudioTracks( writer );
      if( m_doc->mixedType() == K3bMixedDoc::DATA_LAST_TRACK )
	addDataTrack( writer );
    }

    m_writer = writer;
  }
  else {
    if( !writeTocFile() ) {
      kdDebug() << "(K3bDataJob) could not write tocfile." << endl;
      emit infoMessage( i18n("IO Error"), ERROR );

      return false;
    }

    // create the writer
    // create cdrdao job
    K3bCdrdaoWriter* writer = new K3bCdrdaoWriter( m_doc->burner(), this, this );
    writer->setSimulate( m_doc->dummy() );
    writer->setBurnSpeed( m_doc->speed() );

    // multisession only for the first session
    writer->setMulti( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION
		      && m_currentAction == WRITING_AUDIO_IMAGE );

    writer->setTocFile( m_tocFile->name() );

    m_writer = writer;
  }

  connect( m_writer, TQT_SIGNAL(infoMessage(const TQString&, int)), this, TQT_SIGNAL(infoMessage(const TQString&, int)) );
  connect( m_writer, TQT_SIGNAL(percent(int)), this, TQT_SLOT(slotWriterJobPercent(int)) );
  connect( m_writer, TQT_SIGNAL(processedSize(int, int)), this, TQT_SIGNAL(processedSize(int, int)) );
  connect( m_writer, TQT_SIGNAL(subPercent(int)), this, TQT_SIGNAL(subPercent(int)) );
  connect( m_writer, TQT_SIGNAL(processedSubSize(int, int)), this, TQT_SIGNAL(processedSubSize(int, int)) );
  connect( m_writer, TQT_SIGNAL(nextTrack(int, int)), this, TQT_SLOT(slotWriterNextTrack(int, int)) );
  connect( m_writer, TQT_SIGNAL(buffer(int)), this, TQT_SIGNAL(bufferStatus(int)) );
  connect( m_writer, TQT_SIGNAL(deviceBuffer(int)), this, TQT_SIGNAL(deviceBuffer(int)) );
  connect( m_writer, TQT_SIGNAL(writeSpeed(int, int)), this, TQT_SIGNAL(writeSpeed(int, int)) );
  connect( m_writer, TQT_SIGNAL(finished(bool)), this, TQT_SLOT(slotWriterFinished(bool)) );
  //  connect( m_writer, TQT_SIGNAL(newTask(const TQString&)), this, TQT_SIGNAL(newTask(const TQString&)) );
  connect( m_writer, TQT_SIGNAL(newSubTask(const TQString&)), this, TQT_SIGNAL(newSubTask(const TQString&)) );
  connect( m_writer, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)),
	   this, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)) );

  return true;
}


bool K3bMixedJob::writeInfFiles()
{
  K3bInfFileWriter infFileWriter;
  K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
  while( track ) {

    infFileWriter.setTrack( track->toCdTrack() );
    infFileWriter.setTrackNumber( track->trackNumber() );
    if( !m_doc->onTheFly() )
      infFileWriter.setBigEndian( false );

    if( !infFileWriter.save( m_tempData->infFileName(track) ) )
      return false;

    track = track->next();
  }
  return true;
}


bool K3bMixedJob::writeTocFile()
{
  // FIXME: create the tocfile in the same directory like all the other files.

  if( m_tocFile ) delete m_tocFile;
  m_tocFile = new KTempFile( TQString(), "toc" );
  m_tocFile->setAutoDelete(true);

  // write the toc-file
  if( TQTextStream* s = m_tocFile->textStream() ) {

    K3bTocFileWriter tocFileWriter;

    //
    // TOC
    //
    tocFileWriter.setData( m_doc->toToc( m_usedDataMode == K3b::MODE2
					 ? K3bDevice::Track::XA_FORM1
					 : K3bDevice::Track::MODE1,
					 m_doc->onTheFly()
					 ? m_isoImager->size()
					 : m_doc->dataDoc()->length() ) );

    //
    // CD-Text
    //
    if( m_doc->audioDoc()->cdText() ) {
      K3bDevice::CdText text = m_doc->audioDoc()->cdTextData();
      // if data in first track we need to add a dummy cdtext
      if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK )
	text.insert( text.begin(), K3bDevice::TrackCdText() );

      tocFileWriter.setCdText( text );
    }

    //
    // Session to write
    //
    tocFileWriter.setSession( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION &&
			      m_currentAction == WRITING_ISO_IMAGE ? 2 : 1 );

    //
    // image filenames
    //
    if( !m_doc->onTheFly() ) {
      TQStringList files;
      K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
      while( track ) {
	files += m_tempData->bufferFileName( track );
	track = track->next();
      }
      if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK )
	files.prepend( m_isoImageFilePath );
      else
	files.append( m_isoImageFilePath );

      tocFileWriter.setFilenames( files );
    }

    bool success = tocFileWriter.save( *s );

    m_tocFile->close();

    // backup for debugging
//    KIO::NetAccess::del("/tmp/trueg/tocfile_debug_backup.toc",0L);
//    KIO::NetAccess::copy( m_tocFile->name(), "/tmp/trueg/tocfile_debug_backup.toc",0L );

    return success;
  }
  else
    return false;
}


void K3bMixedJob::addAudioTracks( K3bCdrecordWriter* writer )
{
  writer->addArgument( "-useinfo" );

  // add raw cdtext data
  if( m_doc->audioDoc()->cdText() ) {
    writer->setRawCdText( m_doc->audioDoc()->cdTextData().rawPackData() );
  }

  writer->addArgument( "-audio" );

  // we always pad because although K3b makes sure all tracks' length are multiples of 2352
  // it seems that normalize sometimes corrupts these lengths
  // FIXME: see K3bAudioJob for the whole less4secs and zeroPregap handling
  writer->addArgument( "-pad" );

  // Allow tracks shorter than 4 seconds
  writer->addArgument( "-shorttrack" );

  // add all the audio tracks
  K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
  while( track ) {
    if( m_doc->onTheFly() ) {
      // this is only supported by cdrecord versions >= 2.01a13
      writer->addArgument( TQFile::encodeName( m_tempData->infFileName( track ) ) );
    }
    else {
      writer->addArgument( TQFile::encodeName( m_tempData->bufferFileName( track ) ) );
    }
    track = track->next();
  }
}

void K3bMixedJob::addDataTrack( K3bCdrecordWriter* writer )
{
  // add data track
  if(  m_usedDataMode == K3b::MODE2 ) {
    if( k3bcore->externalBinManager()->binObject("cdrecord") &&
	k3bcore->externalBinManager()->binObject("cdrecord")->hasFeature( "xamix" ) )
      writer->addArgument( "-xa" );
    else
      writer->addArgument( "-xa1" );
  }
  else
    writer->addArgument( "-data" );

  if( m_doc->onTheFly() )
    writer->addArgument( TQString("-tsize=%1s").tqarg(m_isoImager->size()) )->addArgument("-");
  else
    writer->addArgument( m_isoImageFilePath );
}


void K3bMixedJob::slotWriterNextTrack( int t, int )
{
  K3bAudioTrack* track = 0;

  if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK ) {
    if( t > 1 )
      track = m_doc->audioDoc()->getTrack(t-1);
  }
  else if( m_doc->mixedType() == K3bMixedDoc::DATA_LAST_TRACK ) {
    if( t < m_doc->audioDoc()->numOfTracks()+1 )
      track = m_doc->audioDoc()->getTrack(t);
  }
  else if( m_currentAction == WRITING_AUDIO_IMAGE )
    track = m_doc->audioDoc()->getTrack(t);
  else
    t = m_doc->numOfTracks();

  if( track )
    emit newSubTask( i18n("Writing track %1 of %2%3")
		     .tqarg(t)
		     .tqarg(m_doc->numOfTracks())
		     .tqarg( track->title().isEmpty() || track->artist().isEmpty()
			   ? TQString()
			   : " (" + track->artist() + " - " + track->title() + ")" ) );
  else
    emit newSubTask( i18n("Writing track %1 of %2 (%3)").tqarg(t).tqarg(m_doc->numOfTracks()).tqarg(i18n("ISO9660 data")) );
}


void K3bMixedJob::slotWriterJobPercent( int p )
{
  double totalTasks = d->copies;
  double tasksDone = d->copiesDone;
  if( m_doc->audioDoc()->normalize() ) {
    totalTasks+=1.0;
    tasksDone+=1.0;
  }
  if( !m_doc->onTheFly() ) {
    totalTasks+=1.0;
  }

  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
    if( m_currentAction == WRITING_AUDIO_IMAGE ) {
      // the audio imager has finished in all cases
      // the iso imager only if this is not the first copy
      if( d->copiesDone > 0 )
	tasksDone += 1.0;
      else if( !m_doc->onTheFly() )
	tasksDone += m_audioDocPartOfProcess;

      p = (int)((double)p*m_audioDocPartOfProcess);
    }
    else {
      // all images have been created
      if( !m_doc->onTheFly() )
	tasksDone += 1.0;

      p = (int)(100.0*m_audioDocPartOfProcess + (double)p*(1.0-m_audioDocPartOfProcess));
    }
  }
  else if( !m_doc->onTheFly() )
    tasksDone += 1.0;

  emit percent( (int)((100.0*tasksDone + (double)p) / totalTasks) );
}


void K3bMixedJob::slotAudioDecoderPercent( int p )
{
  // the only thing finished here might be the isoimager which is part of this task
  if( !m_doc->onTheFly() ) {
    double totalTasks = d->copies+1;
    if( m_doc->audioDoc()->normalize() )
      totalTasks+=1.0;

    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION )
      p = (int)((double)p*m_audioDocPartOfProcess);
    else
      p = (int)(100.0*(1.0-m_audioDocPartOfProcess) + (double)p*m_audioDocPartOfProcess);

    emit percent( (int)((double)p / totalTasks) );
  }
}


void K3bMixedJob::slotAudioDecoderSubPercent( int p )
{
  if( !m_doc->onTheFly() ) {
    emit subPercent( p );
  }
}


void K3bMixedJob::slotIsoImagerPercent( int p )
{
  if( !m_doc->onTheFly() ) {
    emit subPercent( p );
    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {

      double totalTasks = d->copies+1.0;
      double tasksDone = d->copiesDone;
      if( m_doc->audioDoc()->normalize() ) {
	totalTasks+=1.0;
	// the normalizer finished
	tasksDone+=1.0;
      }

      // the writing of the audio part finished
      tasksDone += m_audioDocPartOfProcess;

      // the audio decoder finished (which is part of this task in terms of progress)
      p = (int)(100.0*m_audioDocPartOfProcess + (double)p*(1.0-m_audioDocPartOfProcess));

      emit percent( (int)((100.0*tasksDone + (double)p) / totalTasks) );
    }
    else {
      double totalTasks = d->copies+1.0;
      if( m_doc->audioDoc()->normalize() )
	totalTasks+=1.0;

      emit percent( (int)((double)(p*(1.0-m_audioDocPartOfProcess)) / totalTasks) );
    }
  }
}


bool K3bMixedJob::startWriting()
{
  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
    if( m_currentAction == WRITING_ISO_IMAGE) {
      if( m_doc->dummy() )
	emit newTask( i18n("Simulating second session") );
      else if( d->copies > 1 )
	emit newTask( i18n("Writing second session of copy %1").tqarg(d->copiesDone+1) );
      else
	emit newTask( i18n("Writing second session") );
    }
    else {
      if( m_doc->dummy() )
	emit newTask( i18n("Simulating first session") );
      else if( d->copies > 1 )
	emit newTask( i18n("Writing first session of copy %1").tqarg(d->copiesDone+1) );
      else
	emit newTask( i18n("Writing first session") );
    }
  }
  else if( m_doc->dummy() )
    emit newTask( i18n("Simulating") );
  else
    emit newTask( i18n("Writing Copy %1").tqarg(d->copiesDone+1) );


  // if we append the second session the cd is already in the drive
  if( !(m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION
	&& m_currentAction == WRITING_ISO_IMAGE) ) {

    emit newSubTask( i18n("Waiting for media") );
    if( waitForMedia( m_doc->burner() ) < 0 ) {
      cancel();
      return false;
    }

    // just to be sure we did not get canceled during the async discWaiting
    if( m_canceled )
      return false;

    // check if the project will fit on the CD
    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
      // the media is in and has been checked so this should be fast (hopefully)
      K3b::Msf mediaSize = m_doc->burner()->diskInfo().capacity();
      if( mediaSize < m_projectSize ) {
	if( k3bcore->globalSettings()->overburn() ) {
	  emit infoMessage( i18n("Trying to write more than the official disk capacity"), K3bJob::WARNING );
	}
	else {
	  emit infoMessage( i18n("Data does not fit on disk."), ERROR );
	  return false;
	}
      }
    }
  }

  // in case we determined the max possible writing speed we have to reset the speed on the writer job
  // here since an inserted media is necessary
  // the Max speed job will compare the max speed value with the supported values of the writer
  if( d->maxSpeed )
    m_writer->setBurnSpeed( d->maxSpeedJob->maxSpeed() );

  emit burning(true);
  m_writer->start();

  if( m_doc->onTheFly() ) {
    // now the writer is running and we can get it's stdin
    // we only use this method when writing on-the-fly since
    // we cannot easily change the audioDecode fd while it's working
    // which we would need to do since we write into several
    // image files.
    m_audioImager->writeToFd( m_writer->fd() );
    m_isoImager->writeToFd( m_writer->fd() );
  }

  return true;
}


void K3bMixedJob::createIsoImage()
{
  m_currentAction = CREATING_ISO_IMAGE;

  // prepare iso image file
  m_isoImageFilePath = m_tempFilePrefix + "_datatrack.iso";

  if( !m_doc->onTheFly() )
    emit newTask( i18n("Creating ISO image file") );
  emit newSubTask( i18n("Creating ISO image in %1").tqarg(m_isoImageFilePath) );
  emit infoMessage( i18n("Creating ISO image in %1").tqarg(m_isoImageFilePath), INFO );

  m_isoImager->writeToImageFile( m_isoImageFilePath );
  m_isoImager->start();
}


void K3bMixedJob::cleanupAfterError()
{
  m_errorOccuredAndAlreadyReported = true;
  //  m_audioImager->cancel();
  m_isoImager->cancel();
  if( m_writer )
    m_writer->cancel();

  if( m_tocFile ) delete m_tocFile;
  m_tocFile = 0;

  // remove the temp files
  removeBufferFiles();
}


void K3bMixedJob::removeBufferFiles()
{
    if ( !m_doc->onTheFly() ) {
        emit infoMessage( i18n("Removing buffer files."), INFO );
    }

    if( TQFile::exists( m_isoImageFilePath ) )
        if( !TQFile::remove( m_isoImageFilePath ) )
            emit infoMessage( i18n("Could not delete file %1.").tqarg(m_isoImageFilePath), ERROR );

    // removes buffer images and temp toc or inf files
    m_tempData->cleanup();
}


void K3bMixedJob::determineWritingMode()
{
  // we don't need this when only creating image and it is possible
  // that the burn device is null
  if( m_doc->onlyCreateImages() )
    return;

  // at first we determine the data mode
  // --------------------------------------------------------------
  if( m_doc->dataDoc()->dataMode() == K3b::DATA_MODE_AUTO ) {
    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION )
      m_usedDataMode = K3b::MODE2;
    else
      m_usedDataMode = K3b::MODE1;
  }
  else
    m_usedDataMode = m_doc->dataDoc()->dataMode();


  // we try to use cdrecord if possible
  bool cdrecordOnTheFly = false;
  bool cdrecordCdText = false;
  bool cdrecordUsable = false;

  if( k3bcore->externalBinManager()->binObject("cdrecord") ) {
    cdrecordOnTheFly =
      k3bcore->externalBinManager()->binObject("cdrecord")->hasFeature( "audio-stdin" );
    cdrecordCdText =
      k3bcore->externalBinManager()->binObject("cdrecord")->hasFeature( "cdtext" );
    cdrecordUsable =
      !( !cdrecordOnTheFly && m_doc->onTheFly() ) &&
      !( m_doc->audioDoc()->cdText() && !cdrecordCdText );
  }

  // Writing Application
  // --------------------------------------------------------------
  // cdrecord seems to have problems writing xa 1 disks in dao mode? At least on my system!
  if( writingApp() == K3b::DEFAULT ) {
    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
      if( m_doc->writingMode() == K3b::DAO ||
	  ( m_doc->writingMode() == K3b::WRITING_MODE_AUTO && !cdrecordUsable ) ) {
	m_usedAudioWritingApp = K3b::CDRDAO;
	m_usedDataWritingApp = K3b::CDRDAO;
      }
      else {
	m_usedAudioWritingApp = K3b::CDRECORD;
	m_usedDataWritingApp = K3b::CDRECORD;
      }
    }
    else {
      if( cdrecordUsable ) {
	m_usedAudioWritingApp = K3b::CDRECORD;
	m_usedDataWritingApp = K3b::CDRECORD;
      }
      else {
	m_usedAudioWritingApp = K3b::CDRDAO;
	m_usedDataWritingApp = K3b::CDRDAO;
      }
    }
  }
  else {
    m_usedAudioWritingApp = writingApp();
    m_usedDataWritingApp = writingApp();
  }

  // TODO: use K3bExceptions::brokenDaoAudio

  // Writing Mode (TAO/DAO/RAW)
  // --------------------------------------------------------------
  if( m_doc->writingMode() == K3b::WRITING_MODE_AUTO ) {

    if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
      if( m_usedDataWritingApp == K3b::CDRECORD )
	m_usedDataWritingMode = K3b::TAO;
      else
	m_usedDataWritingMode = K3b::DAO;

      // default to Session at once for the audio part
      m_usedAudioWritingMode = K3b::DAO;
    }
    else if( writer()->dao() ) {
      m_usedDataWritingMode = K3b::DAO;
      m_usedAudioWritingMode = K3b::DAO;
    }
    else {
      m_usedDataWritingMode = K3b::TAO;
      m_usedAudioWritingMode = K3b::TAO;
    }
  }
  else {
    m_usedAudioWritingMode = m_doc->writingMode();
    m_usedDataWritingMode = m_doc->writingMode();
  }


  if( m_usedDataWritingApp == K3b::CDRECORD ) {
    if( !cdrecordOnTheFly && m_doc->onTheFly() ) {
      m_doc->setOnTheFly( false );
      emit infoMessage( i18n("On-the-fly writing with cdrecord < 2.01a13 not supported."), ERROR );
    }

    if( m_doc->audioDoc()->cdText() ) {
      if( !cdrecordCdText ) {
	m_doc->audioDoc()->writeCdText( false );
	emit infoMessage( i18n("Cdrecord %1 does not support CD-Text writing.").tqarg(k3bcore->externalBinManager()->binObject("cdrecord")->version), ERROR );
      }
      else if( m_usedAudioWritingMode == K3b::TAO ) {
	emit infoMessage( i18n("It is not possible to write CD-Text in TAO mode. Try DAO or RAW."), WARNING );
      }
    }
  }
}


void K3bMixedJob::normalizeFiles()
{
  if( !m_normalizeJob ) {
    m_normalizeJob = new K3bAudioNormalizeJob( this, this );

    connect( m_normalizeJob, TQT_SIGNAL(infoMessage(const TQString&, int)),
	     this, TQT_SIGNAL(infoMessage(const TQString&, int)) );
    connect( m_normalizeJob, TQT_SIGNAL(percent(int)), this, TQT_SLOT(slotNormalizeProgress(int)) );
    connect( m_normalizeJob, TQT_SIGNAL(subPercent(int)), this, TQT_SLOT(slotNormalizeSubProgress(int)) );
    connect( m_normalizeJob, TQT_SIGNAL(finished(bool)), this, TQT_SLOT(slotNormalizeJobFinished(bool)) );
    connect( m_normalizeJob, TQT_SIGNAL(newTask(const TQString&)), this, TQT_SIGNAL(newSubTask(const TQString&)) );
    connect( m_normalizeJob, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)),
	     this, TQT_SIGNAL(debuggingOutput(const TQString&, const TQString&)) );
  }

  // add all the files
  TQValueVector<TQString> files;
  K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
  while( track ) {
    files.append( m_tempData->bufferFileName(track) );
    track = track->next();
  }

  m_normalizeJob->setFilesToNormalize( files );

  emit newTask( i18n("Normalizing volume levels") );
  m_normalizeJob->start();
}

void K3bMixedJob::slotNormalizeJobFinished( bool success )
{
  if( m_canceled || m_errorOccuredAndAlreadyReported )
    return;

  if( success ) {
    if( m_doc->mixedType() == K3bMixedDoc::DATA_FIRST_TRACK )
      m_currentAction = WRITING_ISO_IMAGE;
    else
      m_currentAction = WRITING_AUDIO_IMAGE;

    if( !prepareWriter() || !startWriting() ) {
      cleanupAfterError();
      jobFinished(false);
    }
  }
  else {
    cleanupAfterError();
    jobFinished(false);
  }
}

void K3bMixedJob::slotNormalizeProgress( int p )
{
  double totalTasks = d->copies+2.0;
  double tasksDone = 0;

  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION ) {
    // the audio imager finished (m_audioDocPartOfProcess*1 task)
    // plus the normalize progress
    tasksDone = m_audioDocPartOfProcess;
  }
  else {
    // the iso and audio imagers already finished (one task)
    // plus the normalize progress
    tasksDone = 1.0;
  }

  emit percent( (int)((100.0*tasksDone + (double)p) / totalTasks) );
}


void K3bMixedJob::slotNormalizeSubProgress( int p )
{
  emit subPercent( p );
}


void K3bMixedJob::prepareProgressInformation()
{
  // calculate percentage of audio and data
  // this is also used in on-the-fly mode
  double ds = (double)m_doc->dataDoc()->length().totalFrames();
  double as = (double)m_doc->audioDoc()->length().totalFrames();
  m_audioDocPartOfProcess = as/(ds+as);
}


TQString K3bMixedJob::jobDescription() const
{
  if( m_doc->mixedType() == K3bMixedDoc::DATA_SECOND_SESSION )
    return i18n("Writing Enhanced Audio CD")
      + ( m_doc->audioDoc()->title().isEmpty()
	  ? TQString()
	  : TQString( " (%1)" ).tqarg(m_doc->audioDoc()->title()) );
  else
    return i18n("Writing Mixed Mode CD")
      + ( m_doc->audioDoc()->title().isEmpty()
	  ? TQString()
	  : TQString( " (%1)" ).tqarg(m_doc->audioDoc()->title()) );
}


TQString K3bMixedJob::jobDetails() const
{
  return ( i18n("%1 tracks (%2 minutes audio data, %3 ISO9660 data)")
	   .tqarg(m_doc->numOfTracks())
	   .tqarg(m_doc->audioDoc()->length().toString())
	   .tqarg(KIO::convertSize(m_doc->dataDoc()->size()))
	   + ( m_doc->copies() > 1 && !m_doc->dummy()
	       ? i18n(" - %n copy", " - %n copies", m_doc->copies())
	       : TQString() ) );
}

#include "k3bmixedjob.moc"