1 /*
2  * Original author: Uoti Urpala
3  *
4  * This file is part of mpv.
5  *
6  * mpv is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * mpv 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 Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <string.h>
23 #include <dirent.h>
24 #include <inttypes.h>
25 
26 #include "osdep/io.h"
27 
28 #include "mpv_talloc.h"
29 
30 #include "misc/bstr.h"
31 #include "misc/charset_conv.h"
32 #include "common/msg.h"
33 #include "demux/demux.h"
34 #include "options/m_config.h"
35 #include "options/m_option.h"
36 #include "options/path.h"
37 #include "common/common.h"
38 #include "stream/stream.h"
39 #include "timeline.h"
40 
41 #include "cue.h"
42 
43 #define PROBE_SIZE 512
44 
45 #define OPT_BASE_STRUCT struct demux_cue_opts
46 struct demux_cue_opts {
47     char *cue_cp;
48 };
49 
50 const struct m_sub_options demux_cue_conf = {
51         .opts = (const m_option_t[]) {
52             {"codepage", OPT_STRING(cue_cp)},
53             {0}
54         },
55         .size = sizeof(struct demux_cue_opts),
56         .defaults = &(const struct demux_cue_opts) {
57             .cue_cp = "auto"
58         }
59 };
60 
61 struct priv {
62     struct cue_file *f;
63     struct demux_cue_opts *opts;
64 };
65 
add_source(struct timeline * tl,struct demuxer * d)66 static void add_source(struct timeline *tl, struct demuxer *d)
67 {
68     MP_TARRAY_APPEND(tl, tl->sources, tl->num_sources, d);
69 }
70 
try_open(struct timeline * tl,char * filename)71 static bool try_open(struct timeline *tl, char *filename)
72 {
73     struct bstr bfilename = bstr0(filename);
74     // Avoid trying to open itself or another .cue file. Best would be
75     // to check the result of demuxer auto-detection, but the demuxer
76     // API doesn't allow this without opening a full demuxer.
77     if (bstr_case_endswith(bfilename, bstr0(".cue"))
78         || bstrcasecmp(bstr0(tl->demuxer->filename), bfilename) == 0)
79         return false;
80 
81     struct demuxer_params p = {
82         .stream_flags = tl->stream_origin,
83     };
84 
85     struct demuxer *d = demux_open_url(filename, &p, tl->cancel, tl->global);
86     // Since .bin files are raw PCM data with no headers, we have to explicitly
87     // open them. Also, try to avoid to open files that are most likely not .bin
88     // files, as that would only play noise. Checking the file extension is
89     // fragile, but it's about the only way we have.
90     // TODO: maybe also could check if the .bin file is a multiple of the Audio
91     //       CD sector size (2352 bytes)
92     if (!d && bstr_case_endswith(bfilename, bstr0(".bin"))) {
93         MP_WARN(tl, "CUE: Opening as BIN file!\n");
94         p.force_format = "rawaudio";
95         d = demux_open_url(filename, &p, tl->cancel, tl->global);
96     }
97     if (d) {
98         add_source(tl, d);
99         return true;
100     }
101     MP_ERR(tl, "Could not open source '%s'!\n", filename);
102     return false;
103 }
104 
open_source(struct timeline * tl,char * filename)105 static bool open_source(struct timeline *tl, char *filename)
106 {
107     void *ctx = talloc_new(NULL);
108     bool res = false;
109 
110     struct bstr dirname = mp_dirname(tl->demuxer->filename);
111 
112     struct bstr base_filename = bstr0(mp_basename(filename));
113     if (!base_filename.len) {
114         MP_WARN(tl, "CUE: Invalid audio filename in .cue file!\n");
115     } else {
116         char *fullname = mp_path_join_bstr(ctx, dirname, base_filename);
117         if (try_open(tl, fullname)) {
118             res = true;
119             goto out;
120         }
121     }
122 
123     // Try an audio file with the same name as the .cue file (but different
124     // extension).
125     // Rationale: this situation happens easily if the audio file or both files
126     // are renamed.
127 
128     struct bstr cuefile =
129         bstr_strip_ext(bstr0(mp_basename(tl->demuxer->filename)));
130 
131     DIR *d = opendir(bstrdup0(ctx, dirname));
132     if (!d)
133         goto out;
134     struct dirent *de;
135     while ((de = readdir(d))) {
136         char *dename0 = de->d_name;
137         struct bstr dename = bstr0(dename0);
138         if (bstr_case_startswith(dename, cuefile)) {
139             MP_WARN(tl, "CUE: No useful audio filename "
140                     "in .cue file found, trying with '%s' instead!\n",
141                     dename0);
142             if (try_open(tl, mp_path_join_bstr(ctx, dirname, dename))) {
143                 res = true;
144                 break;
145             }
146         }
147     }
148     closedir(d);
149 
150 out:
151     talloc_free(ctx);
152     if (!res)
153         MP_ERR(tl, "CUE: Could not open audio file!\n");
154     return res;
155 }
156 
build_timeline(struct timeline * tl)157 static void build_timeline(struct timeline *tl)
158 {
159     struct priv *p = tl->demuxer->priv;
160 
161     void *ctx = talloc_new(NULL);
162 
163     add_source(tl, tl->demuxer);
164 
165     struct cue_track *tracks = NULL;
166     size_t track_count = 0;
167 
168     for (size_t n = 0; n < p->f->num_tracks; n++) {
169         struct cue_track *track = &p->f->tracks[n];
170         if (track->filename) {
171             MP_TARRAY_APPEND(ctx, tracks, track_count, *track);
172         } else {
173             MP_WARN(tl->demuxer, "No file specified for track entry %zd. "
174                     "It will be removed\n", n + 1);
175         }
176     }
177 
178     if (track_count == 0) {
179         MP_ERR(tl, "CUE: no tracks found!\n");
180         goto out;
181     }
182 
183     // Remove duplicate file entries. This might be too sophisticated, since
184     // CUE files usually use either separate files for every single track, or
185     // only one file for all tracks.
186 
187     char **files = 0;
188     size_t file_count = 0;
189 
190     for (size_t n = 0; n < track_count; n++) {
191         struct cue_track *track = &tracks[n];
192         track->source = -1;
193         for (size_t file = 0; file < file_count; file++) {
194             if (strcmp(files[file], track->filename) == 0) {
195                 track->source = file;
196                 break;
197             }
198         }
199         if (track->source == -1) {
200             file_count++;
201             files = talloc_realloc(ctx, files, char *, file_count);
202             files[file_count - 1] = track->filename;
203             track->source = file_count - 1;
204         }
205     }
206 
207     for (size_t i = 0; i < file_count; i++) {
208         if (!open_source(tl, files[i]))
209             goto out;
210     }
211 
212     struct timeline_part *timeline = talloc_array_ptrtype(tl, timeline,
213                                                           track_count + 1);
214     struct demux_chapter *chapters = talloc_array_ptrtype(tl, chapters,
215                                                           track_count);
216     double starttime = 0;
217     for (int i = 0; i < track_count; i++) {
218         struct demuxer *source = tl->sources[1 + tracks[i].source];
219         double duration;
220         if (i + 1 < track_count && tracks[i].source == tracks[i + 1].source) {
221             duration = tracks[i + 1].start - tracks[i].start;
222         } else {
223             duration = source->duration;
224             // Two cases: 1) last track of a single-file cue, or 2) any track of
225             // a multi-file cue. We need to do this for 1) only because the
226             // timeline needs to be terminated with the length of the last
227             // track.
228             duration -= tracks[i].start;
229         }
230         if (duration < 0) {
231             MP_WARN(tl, "CUE: Can't get duration of source file!\n");
232             // xxx: do something more reasonable
233             duration = 0.0;
234         }
235         timeline[i] = (struct timeline_part) {
236             .start = starttime,
237             .end = starttime + duration,
238             .source_start = tracks[i].start,
239             .source = source,
240         };
241         chapters[i] = (struct demux_chapter) {
242             .pts = timeline[i].start,
243             .metadata = mp_tags_dup(tl, tracks[i].tags),
244         };
245         starttime = timeline[i].end;
246     }
247 
248     struct timeline_par *par = talloc_ptrtype(tl, par);
249     *par = (struct timeline_par){
250         .parts = timeline,
251         .num_parts = track_count,
252         .track_layout = timeline[0].source,
253     };
254 
255     tl->chapters = chapters;
256     tl->num_chapters = track_count;
257     MP_TARRAY_APPEND(tl, tl->pars, tl->num_pars, par);
258     tl->meta = par->track_layout;
259     tl->format = "cue";
260 
261 out:
262     talloc_free(ctx);
263 }
264 
try_open_file(struct demuxer * demuxer,enum demux_check check)265 static int try_open_file(struct demuxer *demuxer, enum demux_check check)
266 {
267     if (!demuxer->access_references)
268         return -1;
269 
270     struct stream *s = demuxer->stream;
271     if (check >= DEMUX_CHECK_UNSAFE) {
272         char probe[PROBE_SIZE];
273         int len = stream_read_peek(s, probe, sizeof(probe));
274         if (len < 1 || !mp_probe_cue((bstr){probe, len}))
275             return -1;
276     }
277     struct priv *p = talloc_zero(demuxer, struct priv);
278     demuxer->priv = p;
279     demuxer->fully_read = true;
280     p->opts = mp_get_config_group(p, demuxer->global, &demux_cue_conf);
281     struct demux_cue_opts *cue_opts = p->opts;
282 
283     bstr data = stream_read_complete(s, p, 1000000);
284     if (data.start == NULL)
285         return -1;
286     const char *charset = mp_charset_guess(p, demuxer->log, data, cue_opts->cue_cp, 0);
287     if (charset && !mp_charset_is_utf8(charset)) {
288         MP_INFO(demuxer, "Using CUE charset: %s\n", charset);
289         bstr utf8 = mp_iconv_to_utf8(demuxer->log, data, charset, MP_ICONV_VERBOSE);
290         if (utf8.start && utf8.start != data.start) {
291             ta_steal(data.start, utf8.start);
292             data = utf8;
293         }
294     }
295     p->f = mp_parse_cue(data);
296     talloc_steal(p, p->f);
297     if (!p->f) {
298         MP_ERR(demuxer, "error parsing input file!\n");
299         return -1;
300     }
301 
302     demux_close_stream(demuxer);
303 
304     mp_tags_merge(demuxer->metadata, p->f->tags);
305     return 0;
306 }
307 
308 const struct demuxer_desc demuxer_desc_cue = {
309     .name = "cue",
310     .desc = "CUE sheet",
311     .open = try_open_file,
312     .load_timeline = build_timeline,
313 };
314