source: josm/trunk/src/org/openstreetmap/josm/gui/layer/gpx/ImportAudioAction.java@ 8510

Last change on this file since 8510 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 13.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer.gpx;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.event.ActionEvent;
8import java.io.File;
9import java.net.URL;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.Comparator;
15
16import javax.swing.AbstractAction;
17import javax.swing.JFileChooser;
18import javax.swing.JOptionPane;
19import javax.swing.filechooser.FileFilter;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.actions.DiskAccessAction;
23import org.openstreetmap.josm.data.gpx.GpxConstants;
24import org.openstreetmap.josm.data.gpx.GpxData;
25import org.openstreetmap.josm.data.gpx.GpxTrack;
26import org.openstreetmap.josm.data.gpx.GpxTrackSegment;
27import org.openstreetmap.josm.data.gpx.WayPoint;
28import org.openstreetmap.josm.gui.HelpAwareOptionPane;
29import org.openstreetmap.josm.gui.layer.GpxLayer;
30import org.openstreetmap.josm.gui.layer.markerlayer.AudioMarker;
31import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
32import org.openstreetmap.josm.gui.widgets.AbstractFileChooser;
33import org.openstreetmap.josm.tools.AudioUtil;
34import org.openstreetmap.josm.tools.ImageProvider;
35import org.openstreetmap.josm.tools.Utils;
36
37/**
38 * Import audio files into a GPX layer to enable audio playback functions.
39 * @since 5715
40 */
41public class ImportAudioAction extends AbstractAction {
42 private final transient GpxLayer layer;
43
44 private static class Markers {
45 public boolean timedMarkersOmitted = false;
46 public boolean untimedMarkersOmitted = false;
47 }
48
49 /**
50 * Constructs a new {@code ImportAudioAction}.
51 * @param layer The associated GPX layer
52 */
53 public ImportAudioAction(final GpxLayer layer) {
54 super(tr("Import Audio"), ImageProvider.get("importaudio"));
55 this.layer = layer;
56 putValue("help", ht("/Action/ImportAudio"));
57 }
58
59 private void warnCantImportIntoServerLayer(GpxLayer layer) {
60 String msg = tr("<html>The data in the GPX layer ''{0}'' has been downloaded from the server.<br>" +
61 "Because its way points do not include a timestamp we cannot correlate them with audio data.</html>",
62 layer.getName());
63 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Import not possible"),
64 JOptionPane.WARNING_MESSAGE, ht("/Action/ImportAudio#CantImportIntoGpxLayerFromServer"));
65 }
66
67 @Override
68 public void actionPerformed(ActionEvent e) {
69 if (layer.data.fromServer) {
70 warnCantImportIntoServerLayer(layer);
71 return;
72 }
73 FileFilter filter = new FileFilter() {
74 @Override
75 public boolean accept(File f) {
76 return f.isDirectory() || Utils.hasExtension(f, "wav");
77 }
78
79 @Override
80 public String getDescription() {
81 return tr("Wave Audio files (*.wav)");
82 }
83 };
84 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, true, null, filter,
85 JFileChooser.FILES_ONLY, "markers.lastaudiodirectory");
86 if (fc != null) {
87 File[] sel = fc.getSelectedFiles();
88 // sort files in increasing order of timestamp (this is the end time, but so
89 // long as they don't overlap, that's fine)
90 if (sel.length > 1) {
91 Arrays.sort(sel, new Comparator<File>() {
92 @Override
93 public int compare(File a, File b) {
94 return a.lastModified() <= b.lastModified() ? -1 : 1;
95 }
96 });
97 }
98 String names = null;
99 for (File file : sel) {
100 if (names == null) {
101 names = " (";
102 } else {
103 names += ", ";
104 }
105 names += file.getName();
106 }
107 if (names != null) {
108 names += ")";
109 } else {
110 names = "";
111 }
112 MarkerLayer ml = new MarkerLayer(new GpxData(), tr("Audio markers from {0}", layer.getName()) + names, layer.getAssociatedFile(), layer);
113 double firstStartTime = sel[0].lastModified() / 1000.0 - AudioUtil.getCalibratedDuration(sel[0]);
114 Markers m = new Markers();
115 for (File file : sel) {
116 importAudio(file, ml, firstStartTime, m);
117 }
118 Main.main.addLayer(ml);
119 Main.map.repaint();
120 }
121 }
122
123 /**
124 * Makes a new marker layer derived from this GpxLayer containing at least one audio marker
125 * which the given audio file is associated with. Markers are derived from the following (a)
126 * explict waypoints in the GPX layer, or (b) named trackpoints in the GPX layer, or (d)
127 * timestamp on the wav file (e) (in future) voice recognised markers in the sound recording (f)
128 * a single marker at the beginning of the track
129 * @param wavFile : the file to be associated with the markers in the new marker layer
130 * @param markers : keeps track of warning messages to avoid repeated warnings
131 */
132 private void importAudio(File wavFile, MarkerLayer ml, double firstStartTime, Markers markers) {
133 URL url = Utils.fileToURL(wavFile);
134 boolean hasTracks = layer.data.tracks != null && !layer.data.tracks.isEmpty();
135 boolean hasWaypoints = layer.data.waypoints != null && !layer.data.waypoints.isEmpty();
136 Collection<WayPoint> waypoints = new ArrayList<>();
137 boolean timedMarkersOmitted = false;
138 boolean untimedMarkersOmitted = false;
139 double snapDistance = Main.pref.getDouble("marker.audiofromuntimedwaypoints.distance", 1.0e-3);
140 // about 25 m
141 WayPoint wayPointFromTimeStamp = null;
142
143 // determine time of first point in track
144 double firstTime = -1.0;
145 if (hasTracks) {
146 for (GpxTrack track : layer.data.tracks) {
147 for (GpxTrackSegment seg : track.getSegments()) {
148 for (WayPoint w : seg.getWayPoints()) {
149 firstTime = w.time;
150 break;
151 }
152 if (firstTime >= 0.0) {
153 break;
154 }
155 }
156 if (firstTime >= 0.0) {
157 break;
158 }
159 }
160 }
161 if (firstTime < 0.0) {
162 JOptionPane.showMessageDialog(
163 Main.parent,
164 tr("No GPX track available in layer to associate audio with."),
165 tr("Error"),
166 JOptionPane.ERROR_MESSAGE
167 );
168 return;
169 }
170
171 // (a) try explicit timestamped waypoints - unless suppressed
172 if (Main.pref.getBoolean("marker.audiofromexplicitwaypoints", true) && hasWaypoints) {
173 for (WayPoint w : layer.data.waypoints) {
174 if (w.time > firstTime) {
175 waypoints.add(w);
176 } else if (w.time > 0.0) {
177 timedMarkersOmitted = true;
178 }
179 }
180 }
181
182 // (b) try explicit waypoints without timestamps - unless suppressed
183 if (Main.pref.getBoolean("marker.audiofromuntimedwaypoints", true) && hasWaypoints) {
184 for (WayPoint w : layer.data.waypoints) {
185 if (waypoints.contains(w)) {
186 continue;
187 }
188 WayPoint wNear = layer.data.nearestPointOnTrack(w.getEastNorth(), snapDistance);
189 if (wNear != null) {
190 WayPoint wc = new WayPoint(w.getCoor());
191 wc.time = wNear.time;
192 if (w.attr.containsKey(GpxConstants.GPX_NAME)) {
193 wc.put(GpxConstants.GPX_NAME, w.getString(GpxConstants.GPX_NAME));
194 }
195 waypoints.add(wc);
196 } else {
197 untimedMarkersOmitted = true;
198 }
199 }
200 }
201
202 // (c) use explicitly named track points, again unless suppressed
203 if ((Main.pref.getBoolean("marker.audiofromnamedtrackpoints", false)) && layer.data.tracks != null
204 && !layer.data.tracks.isEmpty()) {
205 for (GpxTrack track : layer.data.tracks) {
206 for (GpxTrackSegment seg : track.getSegments()) {
207 for (WayPoint w : seg.getWayPoints()) {
208 if (w.attr.containsKey(GpxConstants.GPX_NAME) || w.attr.containsKey(GpxConstants.GPX_DESC)) {
209 waypoints.add(w);
210 }
211 }
212 }
213 }
214 }
215
216 // (d) use timestamp of file as location on track
217 if ((Main.pref.getBoolean("marker.audiofromwavtimestamps", false)) && hasTracks) {
218 double lastModified = wavFile.lastModified() / 1000.0; // lastModified is in
219 // milliseconds
220 double duration = AudioUtil.getCalibratedDuration(wavFile);
221 double startTime = lastModified - duration;
222 startTime = firstStartTime + (startTime - firstStartTime)
223 / Main.pref.getDouble("audio.calibration", 1.0 /* default, ratio */);
224 WayPoint w1 = null;
225 WayPoint w2 = null;
226
227 for (GpxTrack track : layer.data.tracks) {
228 for (GpxTrackSegment seg : track.getSegments()) {
229 for (WayPoint w : seg.getWayPoints()) {
230 if (startTime < w.time) {
231 w2 = w;
232 break;
233 }
234 w1 = w;
235 }
236 if (w2 != null) {
237 break;
238 }
239 }
240 }
241
242 if (w1 == null || w2 == null) {
243 timedMarkersOmitted = true;
244 } else {
245 wayPointFromTimeStamp = new WayPoint(w1.getCoor().interpolate(w2.getCoor(),
246 (startTime - w1.time) / (w2.time - w1.time)));
247 wayPointFromTimeStamp.time = startTime;
248 String name = wavFile.getName();
249 int dot = name.lastIndexOf('.');
250 if (dot > 0) {
251 name = name.substring(0, dot);
252 }
253 wayPointFromTimeStamp.put(GpxConstants.GPX_NAME, name);
254 waypoints.add(wayPointFromTimeStamp);
255 }
256 }
257
258 // (e) analyse audio for spoken markers here, in due course
259
260 // (f) simply add a single marker at the start of the track
261 if ((Main.pref.getBoolean("marker.audiofromstart") || waypoints.isEmpty()) && hasTracks) {
262 boolean gotOne = false;
263 for (GpxTrack track : layer.data.tracks) {
264 for (GpxTrackSegment seg : track.getSegments()) {
265 for (WayPoint w : seg.getWayPoints()) {
266 WayPoint wStart = new WayPoint(w.getCoor());
267 wStart.put(GpxConstants.GPX_NAME, "start");
268 wStart.time = w.time;
269 waypoints.add(wStart);
270 gotOne = true;
271 break;
272 }
273 if (gotOne) {
274 break;
275 }
276 }
277 if (gotOne) {
278 break;
279 }
280 }
281 }
282
283 /* we must have got at least one waypoint now */
284
285 Collections.sort((ArrayList<WayPoint>) waypoints, new Comparator<WayPoint>() {
286 @Override
287 public int compare(WayPoint a, WayPoint b) {
288 return a.time <= b.time ? -1 : 1;
289 }
290 });
291
292 firstTime = -1.0; /* this time of the first waypoint, not first trackpoint */
293 for (WayPoint w : waypoints) {
294 if (firstTime < 0.0) {
295 firstTime = w.time;
296 }
297 double offset = w.time - firstTime;
298 AudioMarker am = new AudioMarker(w.getCoor(), w, url, ml, w.time, offset);
299 /*
300 * timeFromAudio intended for future use to shift markers of this type on
301 * synchronization
302 */
303 if (w == wayPointFromTimeStamp) {
304 am.timeFromAudio = true;
305 }
306 ml.data.add(am);
307 }
308
309 if (timedMarkersOmitted && !markers.timedMarkersOmitted) {
310 JOptionPane
311 .showMessageDialog(
312 Main.parent,
313 tr("Some waypoints with timestamps from before the start of the track or after the end were omitted or moved to the start."));
314 markers.timedMarkersOmitted = timedMarkersOmitted;
315 }
316 if (untimedMarkersOmitted && !markers.untimedMarkersOmitted) {
317 JOptionPane
318 .showMessageDialog(
319 Main.parent,
320 tr("Some waypoints which were too far from the track to sensibly estimate their time were omitted."));
321 markers.untimedMarkersOmitted = untimedMarkersOmitted;
322 }
323 }
324}
Note: See TracBrowser for help on using the repository browser.