Debian Codegraph @

src/jobs/joblist/addfiles.cpp

raw symbols SCIP
1 /* fre:ac - free audio converter
2 * Copyright (C) 2001-2023 Robert Kausch <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation, either version 2 of
7 * the License, or (at your option) any later version.
8 *
9 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
10 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
11 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
12
13 #include <jobs/joblist/addfiles.h>
14 #include <jobs/joblist/removeall.h>
15
16 #include <dialogs/cddb/query.h>
17
18 #include <config.h>
19 #include <utilities.h>
20
21 #include <support/autorelease.h>
22
23 using namespace smooth::IO;
24 using namespace smooth::Threads;
25
26 using namespace BoCA;
27 using namespace BoCA::AS;
28
29 namespace freac
30 {
31 class JobAddFilesWorker : public Thread
32 {
33 private:
34 String fileName;
35 Semaphore &semaphore;
36
37 Track track;
38 Bool ready;
39
40 Bool errorState;
41 String errorString;
42
43 Int Run();
44
45 static Void ExtractInfoFromPath(const String &, Info &);
46 public:
47 JobAddFilesWorker(const String &, Semaphore &);
48
49 Bool IsReady() const { return ready; }
50 const Track &GetTrack() const { return track; }
51
52 Bool GetErrorState() const { return errorState; }
53 const String &GetErrorString() const { return errorString; }
54 };
55 };
56
57 freac::JobAddFiles::JobAddFiles(const Array<String> &iFiles)
58 {
59 BoCA::I18n *i18n = BoCA::I18n::Get();
60
61 i18n->SetContext("Jobs");
62
63 foreach (const String &file, iFiles) files.Add(file);
64
65 JobRemoveAllTracks::onRemoveAllTracksJobScheduled.Connect(&Job::RequestAbort, this);
66
67 SetText(i18n->AddEllipsis(i18n->TranslateString("Waiting for other jobs to finish")));
68 }
69
70 freac::JobAddFiles::~JobAddFiles()
71 {
72 JobRemoveAllTracks::onRemoveAllTracksJobScheduled.Disconnect(&Job::RequestAbort, this);
73 }
74
75 Bool freac::JobAddFiles::ReadyToRun()
76 {
77 BoCA::JobList *joblist = BoCA::JobList::Get();
78
79 if (joblist->IsLocked()) return False;
80
81 JobList::Get()->Lock();
82
83 return True;
84 }
85
86 Error freac::JobAddFiles::Perform()
87 {
88 BoCA::JobList *joblist = BoCA::JobList::Get();
89 BoCA::I18n *i18n = BoCA::I18n::Get();
90
91 Array<CDDBInfo> cdInfos;
92 Array<Bool> cddbsQueried;
93
94 /* Get number of threads to use.
95 */
96 Bool enableParallel = configuration->GetIntValue(Config::CategoryResourcesID, Config::ResourcesEnableParallelConversionsID, Config::ResourcesEnableParallelConversionsDefault);
97 Int numberOfThreads = configuration->GetIntValue(Config::CategoryResourcesID, Config::ResourcesNumberOfConversionThreadsID, Config::ResourcesNumberOfConversionThreadsDefault);
98
99 if (!enableParallel) numberOfThreads = 1;
100 else if (numberOfThreads <= 1) numberOfThreads = CPU().GetNumCores() + (CPU().GetNumLogicalCPUs() - CPU().GetNumCores()) / 2;
101
102 /* Process and add files.
103 */
104 Array<JobAddFilesWorker *> workers;
105 Semaphore semaphore(numberOfThreads);
106
107 for (Int i = 0; (i < files.Length() && !abort) || workers.Length() > 0; )
108 {
109 AutoRelease autoRelease;
110
111 /* Start next worker.
112 */
113 if (i < files.Length() && !abort)
114 {
115 /* Wait for a free slot.
116 */
117 semaphore.Wait();
118
119 /* Get file name.
120 */
121 const String &file = files.GetNth(i++);
122
123 SetText(i18n->AddEllipsis(i18n->TranslateString("Adding files", "Jobs::Joblist")).Append(" - ").Append(file));
124
125 /* Create and start worker thread.
126 */
127 workers.Add(new JobAddFilesWorker(file, semaphore));
128 workers.GetLast()->Start();
129 }
130
131 /* Finish when no more workers left.
132 */
133 if (workers.Length() == 0) break;
134
135 /* Check for finished worker.
136 */
137 JobAddFilesWorker *worker = workers.GetFirst();
138
139 if (worker->IsReady())
140 {
141 /* Remove worker from queue and check for error.
142 */
143 workers.RemoveNth(0);
144 worker->Wait();
145
146 if (worker->GetErrorState()) errors.Add(worker->GetErrorString());
147
148 /* Get track from worker.
149 */
150 Track track = worker->GetTrack();
151
152 if (track != NIL && !worker->GetErrorState() && !abort)
153 {
154 /* Query CDDB and update track info.
155 */
156 if (track.isCDTrack && configuration->GetIntValue(Config::CategoryFreedbID, Config::FreedbAutoQueryID, Config::FreedbAutoQueryDefault))
157 {
158 if (!cddbsQueried.Get(track.discid))
159 {
160 cdInfos.Add(cddbQueryDlg::QueryCDDB(track, True), track.discid);
161 cddbsQueried.Add(True, track.discid);
162 }
163
164 const CDDBInfo &cdInfo = cdInfos.Get(track.discid);
165
166 if (cdInfo != NIL) cdInfo.UpdateTrack(track);
167 }
168
169 /* Add track(s) to joblist.
170 */
171 if (track.tracks.Length() > 0) foreach (const Track &iTrack, track.tracks) joblist->onComponentAddTrack.Emit(iTrack);
172 else joblist->onComponentAddTrack.Emit(track);
173
174 SetProgress((i - workers.Length() + 1) * 1000 / files.Length());
175 }
176
177 /* Delete worker.
178 */
179 delete worker;
180 }
181 }
182
183 if (abort) errors.RemoveAll();
184
185 if (!abort)
186 {
187 SetText(i18n->TranslateString("Added %1 files, %2 errors occurred", "Jobs::Joblist").Replace("%1", String::FromInt(files.Length() - errors.Length())).Replace("%2", String::FromInt(errors.Length())));
188 SetProgress(1000);
189 }
190
191 files.RemoveAll();
192
193 joblist->Unlock();
194
195 return Success();
196 }
197
198 freac::JobAddFilesWorker::JobAddFilesWorker(const String &iFileName, Semaphore &iSemaphore) : semaphore(iSemaphore)
199 {
200 fileName = iFileName;
201 ready = False;
202
203 errorState = False;
204
205 threadMain.Connect(&JobAddFilesWorker::Run, this);
206 }
207
208 Int freac::JobAddFilesWorker::Run()
209 {
210 BoCA::Config *config = BoCA::Config::Get();
211 Registry &boca = Registry::Get();
212
213 /* Check access permission.
214 */
215 InStream in(STREAM_FILE, fileName, IS_READ);
216
217 if (in.GetLastError() == IO_ERROR_NOACCESS)
218 {
219 BoCA::I18n *i18n = BoCA::I18n::Get();
220
221 i18n->SetContext("Errors");
222
223 errorState = True;
224 errorString = i18n->TranslateString("Unable to open file: %1\n\nError: %2").Replace("%1", File(fileName).GetFileName()).Replace("%2", i18n->TranslateString("Access denied"));
225 }
226
227 in.Close();
228
229 /* Create decoder component.
230 */
231 DecoderComponent *decoder = NIL;
232
233 if (!errorState)
234 {
235 decoder = boca.CreateDecoderForStream(fileName);
236
237 if (decoder == NIL)
238 {
239 BoCA::I18n *i18n = BoCA::I18n::Get();
240
241 i18n->SetContext("Errors");
242
243 errorState = True;
244 errorString = i18n->TranslateString("Unable to open file: %1\n\nError: %2").Replace("%1", File(fileName).GetFileName()).Replace("%2", i18n->TranslateString("Unknown file type"));
245 }
246 }
247
248 /* Query stream info.
249 */
250 if (!errorState)
251 {
252 Error error = decoder->GetStreamInfo(fileName, track);
253 String errorText = decoder->GetErrorString();
254
255 boca.DeleteComponent(decoder);
256
257 if (error == Error())
258 {
259 BoCA::I18n *i18n = BoCA::I18n::Get();
260
261 i18n->SetContext("Errors");
262
263 errorState = True;
264 errorString = i18n->TranslateString("Unable to open file: %1\n\nError: %2").Replace("%1", File(fileName).GetFileName()).Replace("%2", i18n->TranslateString(errorText));
265 }
266 }
267
268 /* Process track.
269 */
270 Bool extractFromFileNames = config->GetIntValue(Config::CategoryTagsID, Config::TagsExtractFromFileNamesID, Config::TagsExtractFromFileNamesDefault);
271
272 if (!errorState)
273 {
274 /* Add disc ID to CD tracks.
275 */
276 if (track.isCDTrack) track.discid = CDDB::DiscIDFromMCDI(track.GetInfo().mcdi);
277
278 /* Extract title info from path names.
279 */
280 Info info = track.GetInfo();
281
282 if (extractFromFileNames && !fileName.StartsWith("device://")) ExtractInfoFromPath(fileName, info);
283
284 track.SetInfo(info);
285
286 /* Add album art from external files.
287 */
288 track.LoadCoverArtFiles();
289 }
290
291 Access::Set(ready, True);
292
293 semaphore.Release();
294
295 if (errorState) return Error();
296 else return Success();
297 }
298
299 Void freac::JobAddFilesWorker::ExtractInfoFromPath(const String &path, Info &info)
300 {
301 /* Check if there is any metadata missing.
302 */
303 if (info.artist != NIL && info.album != NIL && info.disc > 0 && info.track > 0 && info.title != NIL) return;
304
305 /* Get file and folder name and remove extension.
306 */
307 String fileName = File(path).GetFileName().Replace("_", " ");
308 String folderName = Directory(File(path).GetFilePath()).GetDirectoryName();
309
310 if (fileName.FindLast(".") >= 0) fileName = fileName.Head(fileName.FindLast("."));
311
312 /* Check if folder might name a disc number.
313 */
314 Info pathInfo;
315
316 if (!folderName.Contains(" - "))
317 {
318 BoCA::I18n *i18n = BoCA::I18n::Get();
319
320 Int words = folderName.Explode(" ").Length();
321 Int number = 0;
322 Int numbers = 0;
323 Bool keyword = folderName.ToUpper().Contains("CD") ||
324 folderName.ToLower().Contains("disc") ||
325 folderName.ToLower().Contains(i18n->TranslateString("Disc").ToLower());
326
327 for (Int i = 0; i < folderName.Length(); i++)
328 {
329 if (folderName[i] < '1' || folderName[i] > '9') continue;
330
331 if (++numbers == 1) number = folderName.Tail(folderName.Length() - i).ToInt();
332
333 while (folderName[i + 1] >= '1' && folderName[i + 1] <= '9') i++;
334 }
335
336 /* Strip last element from folder name and assign disc number.
337 */
338 if (numbers == 1 && (keyword || words <= 2))
339 {
340 folderName = Directory(Directory(File(path).GetFilePath()).GetDirectoryPath()).GetDirectoryName();
341 pathInfo.disc = number;
342 }
343 }
344
345 /* Split file and folder names at " - ".
346 */
347 const Array<String> &fileElements = fileName.Explode(" - ");
348 const Array<String> &folderElements = folderName.Explode(" - ");
349
350 /* Assume folder name contains artist and album name.
351 */
352 pathInfo.artist = folderName;
353
354 if (folderElements.Length() >= 2)
355 {
356 pathInfo.artist = folderElements.GetFirst();
357 pathInfo.album = folderName.Tail(folderName.Length() - pathInfo.artist.Length() - 3);
358 }
359
360 /* Check file name contents.
361 */
362 pathInfo.title = fileName;
363
364 const String &first = fileElements.GetFirst();
365
366 if (first[0] >= '1' && first[0] <= '9' && (first[1] == ' ' || first[1] == '.' || first[1] == '-') && (first[2] < '0' || first[2] > '9'))
367 {
368 pathInfo.track = first.ToInt();
369
370 if (fileElements.Length() == 1) pathInfo.title = first.Tail(first.Length() - 2).Trim();
371 else if (fileElements.Length() >= 2) { pathInfo.artist = first.Tail(first.Length() - 2).Trim(); pathInfo.title = fileElements.GetLast(); }
372 }
373 else if (first[0] >= '0' && first[0] <= '9' && first[1] >= '0' && first[1] <= '9' && (first[2] == ' ' || first[2] == '.' || first[2] == '-') && (first[3] < '0' || first[3] > '9'))
374 {
375 pathInfo.track = first.ToInt();
376
377 if (fileElements.Length() == 1) pathInfo.title = first.Tail(first.Length() - 3).Trim();
378 else if (fileElements.Length() >= 2) { pathInfo.artist = first.Tail(first.Length() - 3).Trim(); pathInfo.title = fileElements.GetLast(); }
379 }
380 else if (first[0] >= '0' && first[0] <= '9' && first[1] >= '0' && first[1] <= '9' && first.Length() == 2)
381 {
382 pathInfo.track = first.ToInt();
383
384 if (fileElements.Length() == 2) pathInfo.title = fileElements.GetLast();
385 else if (fileElements.Length() >= 3) { pathInfo.artist = fileElements.GetNth(1); pathInfo.title = fileElements.GetLast(); }
386 }
387 else if (first[0] >= '1' && first[0] <= '9' && first[1] >= '0' && first[1] <= '9' && first[2] >= '0' && first[2] <= '9' && (first[3] == ' ' || first[3] == '.' || first[3] == '-') && (first[4] < '0' || first[4] > '9'))
388 {
389 pathInfo.disc = first.ToInt() / 100;
390 pathInfo.track = first.ToInt() % 100;
391
392 if (fileElements.Length() == 1) pathInfo.title = first.Tail(first.Length() - 4).Trim();
393 else if (fileElements.Length() >= 2) { pathInfo.artist = first.Tail(first.Length() - 4).Trim(); pathInfo.title = fileElements.GetLast(); }
394 }
395 else if (first[0] >= '1' && first[0] <= '9' && first[1] >= '0' && first[1] <= '9' && first[2] >= '0' && first[2] <= '9' && first.Length() == 3)
396 {
397 pathInfo.disc = first.ToInt() / 100;
398 pathInfo.track = first.ToInt() % 100;
399
400 if (fileElements.Length() == 2) pathInfo.title = fileElements.GetLast();
401 else if (fileElements.Length() >= 3) { pathInfo.artist = fileElements.GetNth(1); pathInfo.title = fileElements.GetLast(); }
402 }
403 else if (fileElements.Length() == 4)
404 {
405 const String &second = fileElements.GetNth(1);
406 const String &third = fileElements.GetNth(2);
407
408 if (second[0] >= '0' && second[0] <= '9' && second[1] >= '0' && second[1] <= '9' && second.Length() == 2)
409 {
410 pathInfo.album = fileElements.GetFirst();
411 pathInfo.track = fileElements.GetNth(1).ToInt();
412 pathInfo.artist = fileElements.GetNth(2);
413 pathInfo.title = fileElements.GetLast();
414 }
415 else if (third[0] >= '0' && third[0] <= '9' && third[1] >= '0' && third[1] <= '9' && third.Length() == 2)
416 {
417 pathInfo.artist = fileElements.GetFirst();
418 pathInfo.album = fileElements.GetNth(1);
419 pathInfo.track = fileElements.GetNth(2).ToInt();
420 pathInfo.title = fileElements.GetLast();
421 }
422 }
423 else if (fileElements.Length() >= 2)
424 {
425 pathInfo.artist = fileElements.GetFirst();
426 pathInfo.title = fileElements.GetLast();
427
428 foreach (const String &element, fileElements)
429 {
430 if (element[0] >= '0' && element[0] <= '9' && element[1] >= '0' && element[1] <= '9' && element.Length() == 2) pathInfo.track = element.ToInt();
431 }
432 }
433
434 /* Clean up title.
435 */
436 Int length = pathInfo.title.Length();
437
438 if (pathInfo.title[length - 4] == '-' && pathInfo.title[length - 3] >= 'a' && pathInfo.title[length - 3] <= 'z' && pathInfo.title[length - 2] >= 'a' && pathInfo.title[length - 2] <= 'z' && pathInfo.title[length - 1] >= 'a' && pathInfo.title[length - 1] <= 'z') pathInfo.title = pathInfo.title.Head(pathInfo.title.Length() - 4);
439 if (pathInfo.title.ToLower().StartsWith(pathInfo.artist.ToLower().Append("-"))) pathInfo.title = pathInfo.title.Tail(pathInfo.title.Length() - pathInfo.artist.Length() - 1);
440
441 /* Update file metadata.
442 */
443 if (info.artist == NIL) info.artist = pathInfo.artist;
444 if (info.album == NIL) info.album = pathInfo.album;
445 if (info.disc <= 0) info.disc = pathInfo.disc;
446 if (info.track <= 0) info.track = pathInfo.track;
447 if (info.title == NIL) info.title = pathInfo.title;
448 }