summaryrefslogtreecommitdiffstats
path: root/xbmc/cdrip/CDDARipJob.cpp
blob: d8cbab93aba98cb4195393a2a1e756151a410ec1 (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
/*
 *  Copyright (C) 2012-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "CDDARipJob.h"

#include "Encoder.h"
#include "EncoderAddon.h"
#include "EncoderFFmpeg.h"
#include "FileItem.h"
#include "ServiceBroker.h"
#include "Util.h"
#include "addons/AddonManager.h"
#include "addons/addoninfo/AddonType.h"
#include "dialogs/GUIDialogExtendedProgressBar.h"
#include "filesystem/File.h"
#include "filesystem/SpecialProtocol.h"
#include "guilib/GUIComponent.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/LocalizeStrings.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "storage/MediaManager.h"
#include "utils/StringUtils.h"
#include "utils/SystemInfo.h"
#include "utils/log.h"

#if defined(TARGET_WINDOWS)
#include "platform/win32/CharsetConverter.h"
#endif

using namespace ADDON;
using namespace MUSIC_INFO;
using namespace XFILE;
using namespace KODI::CDRIP;

CCDDARipJob::CCDDARipJob(const std::string& input,
                         const std::string& output,
                         const CMusicInfoTag& tag,
                         int encoder,
                         bool eject,
                         unsigned int rate,
                         unsigned int channels,
                         unsigned int bps)
  : m_rate(rate),
    m_channels(channels),
    m_bps(bps),
    m_tag(tag),
    m_input(input),
    m_output(CUtil::MakeLegalPath(output)),
    m_eject(eject),
    m_encoder(encoder)
{
}

CCDDARipJob::~CCDDARipJob() = default;

bool CCDDARipJob::DoWork()
{
  CLog::Log(LOGINFO, "CCDDARipJob::{} - Start ripping track {} to {}", __func__, m_input, m_output);

  // if we are ripping to a samba share, rip it to hd first and then copy it to the share
  CFileItem file(m_output, false);
  if (file.IsRemote())
    m_output = SetupTempFile();

  if (m_output.empty())
  {
    CLog::Log(LOGERROR, "CCDDARipJob::{} - Error opening file", __func__);
    return false;
  }

  // init ripper
  CFile reader;
  std::unique_ptr<CEncoder> encoder{};
  if (!reader.Open(m_input, READ_CACHED) || !(encoder = SetupEncoder(reader)))
  {
    CLog::Log(LOGERROR, "CCDDARipJob::{} - Opening failed", __func__);
    return false;
  }

  // setup the progress dialog
  CGUIDialogExtendedProgressBar* pDlgProgress =
      CServiceBroker::GetGUI()->GetWindowManager().GetWindow<CGUIDialogExtendedProgressBar>(
          WINDOW_DIALOG_EXT_PROGRESS);
  CGUIDialogProgressBarHandle* handle = pDlgProgress->GetHandle(g_localizeStrings.Get(605));

  int iTrack = atoi(m_input.substr(13, m_input.size() - 13 - 5).c_str());
  std::string strLine0 =
      StringUtils::Format("{:02}. {} - {}", iTrack, m_tag.GetArtistString(), m_tag.GetTitle());
  handle->SetText(strLine0);

  // start ripping
  int percent = 0;
  int oldpercent = 0;
  bool cancelled(false);
  int result;
  while (!cancelled && (result = RipChunk(reader, encoder, percent)) == 0)
  {
    cancelled = ShouldCancel(percent, 100);
    if (percent > oldpercent)
    {
      oldpercent = percent;
      handle->SetPercentage(static_cast<float>(percent));
    }
  }

  // close encoder ripper
  encoder->EncoderClose();
  encoder.reset();
  reader.Close();

  if (file.IsRemote() && !cancelled && result == 2)
  {
    // copy the ripped track to the share
    if (!CFile::Copy(m_output, file.GetPath()))
    {
      CLog::Log(LOGERROR, "CCDDARipJob::{} - Error copying file from {} to {}", __func__, m_output,
                file.GetPath());
      CFile::Delete(m_output);
      return false;
    }
    // delete cached file
    CFile::Delete(m_output);
  }

  if (cancelled)
  {
    CLog::Log(LOGWARNING, "CCDDARipJob::{} - User Cancelled CDDA Rip", __func__);
    CFile::Delete(m_output);
  }
  else if (result == 1)
    CLog::Log(LOGERROR, "CCDDARipJob::{} - Error ripping {}", __func__, m_input);
  else if (result < 0)
    CLog::Log(LOGERROR, "CCDDARipJob::{} - Error encoding {}", __func__, m_input);
  else
  {
    CLog::Log(LOGINFO, "CCDDARipJob::{} - Finished ripping {}", __func__, m_input);
    if (m_eject)
    {
      CLog::Log(LOGINFO, "CCDDARipJob::{} - Ejecting CD", __func__);
      CServiceBroker::GetMediaManager().EjectTray();
    }
  }

  handle->MarkFinished();

  return !cancelled && result == 2;
}

int CCDDARipJob::RipChunk(CFile& reader, const std::unique_ptr<CEncoder>& encoder, int& percent)
{
  percent = 0;

  uint8_t stream[1024];

  // get data
  ssize_t result = reader.Read(stream, 1024);

  // return if rip is done or on some kind of error
  if (result <= 0)
    return 1;

  // encode data
  ssize_t encres = encoder->EncoderEncode(stream, result);

  // Get progress indication
  percent = static_cast<int>(reader.GetPosition() * 100 / reader.GetLength());

  if (reader.GetPosition() == reader.GetLength())
    return 2;

  return -(1 - encres);
}

std::unique_ptr<CEncoder> CCDDARipJob::SetupEncoder(CFile& reader)
{
  std::unique_ptr<CEncoder> encoder;
  const std::string audioEncoder = CServiceBroker::GetSettingsComponent()->GetSettings()->GetString(
      CSettings::SETTING_AUDIOCDS_ENCODER);
  if (audioEncoder == "audioencoder.kodi.builtin.aac" ||
      audioEncoder == "audioencoder.kodi.builtin.wma")
  {
    encoder = std::make_unique<CEncoderFFmpeg>();
  }
  else
  {
    const AddonInfoPtr addonInfo =
        CServiceBroker::GetAddonMgr().GetAddonInfo(audioEncoder, AddonType::AUDIOENCODER);
    if (addonInfo)
    {
      encoder = std::make_unique<CEncoderAddon>(addonInfo);
    }
  }
  if (!encoder)
    return std::unique_ptr<CEncoder>{};

  // we have to set the tags before we init the Encoder
  const std::string strTrack = StringUtils::Format(
      "{}", std::stol(m_input.substr(13, m_input.size() - 13 - 5), nullptr, 10));

  const std::string itemSeparator =
      CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_musicItemSeparator;

  encoder->SetComment(std::string("Ripped with ") + CSysInfo::GetAppName());
  encoder->SetArtist(StringUtils::Join(m_tag.GetArtist(), itemSeparator));
  encoder->SetTitle(m_tag.GetTitle());
  encoder->SetAlbum(m_tag.GetAlbum());
  encoder->SetAlbumArtist(StringUtils::Join(m_tag.GetAlbumArtist(), itemSeparator));
  encoder->SetGenre(StringUtils::Join(m_tag.GetGenre(), itemSeparator));
  encoder->SetTrack(strTrack);
  encoder->SetTrackLength(static_cast<int>(reader.GetLength()));
  encoder->SetYear(m_tag.GetYearString());

  // init encoder
  if (!encoder->EncoderInit(m_output, m_channels, m_rate, m_bps))
    encoder.reset();

  return encoder;
}

std::string CCDDARipJob::SetupTempFile()
{
  char tmp[MAX_PATH + 1];
#if defined(TARGET_WINDOWS)
  using namespace KODI::PLATFORM::WINDOWS;
  wchar_t tmpW[MAX_PATH];
  GetTempFileName(ToW(CSpecialProtocol::TranslatePath("special://temp/")).c_str(), L"riptrack", 0,
                  tmpW);
  auto tmpString = FromW(tmpW);
  strncpy_s(tmp, tmpString.length(), tmpString.c_str(), MAX_PATH);
#else
  int fd;
  strncpy(tmp, CSpecialProtocol::TranslatePath("special://temp/riptrackXXXXXX").c_str(), MAX_PATH);
  if ((fd = mkstemp(tmp)) == -1)
    tmp[0] = '\0';
  if (fd != -1)
    close(fd);
#endif
  return tmp;
}

bool CCDDARipJob::operator==(const CJob* job) const
{
  if (strcmp(job->GetType(), GetType()) == 0)
  {
    const CCDDARipJob* rjob = dynamic_cast<const CCDDARipJob*>(job);
    if (rjob)
    {
      return m_input == rjob->m_input && m_output == rjob->m_output;
    }
  }
  return false;
}