Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js"),
  6. timestamp,
  7. identifier;
  8. function addZero (digit) {
  9. if (digit.toString().length === 1) {
  10. return '0' + digit.toString();
  11. }
  12. else {
  13. return digit.toString();
  14. }
  15. }
  16. function timestamp () {
  17. var d = new Date();
  18. return addZero(d.getMonth() + 1)
  19. + addZero(d.getDate())
  20. + d.getFullYear().toString().slice(2,4) + '_'
  21. + addZero(d.getHours())
  22. + addZero(d.getMinutes())
  23. + addZero(d.getSeconds()) + '_';
  24. }
  25. var pre_pro = window.location.protocol,
  26. pre_host = window.location.host;
  27. d3.json(pre_pro + "//" + pre_host + "/settings/labels.json", function(err, labels){
  28. // Populate labels menu
  29. d3.select("#input-label")
  30. .on("change", updateLabel)
  31. .selectAll("option")
  32. .data(labels.podcasts)
  33. .enter()
  34. .append("option")
  35. .text(function(l){
  36. return l;
  37. });
  38. d3.select("#input-label").each(updateLabel);
  39. }); // end label ingestion
  40. d3.json(pre_pro + "//" + pre_host + "/settings/themes.json", function(err, themes){
  41. var errorMessage;
  42. // Themes are missing or invalid
  43. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  44. if (err instanceof SyntaxError) {
  45. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  46. } else if (err instanceof ProgressEvent) {
  47. errorMessage = "Error: no settings/themes.json.";
  48. } else if (err) {
  49. errorMessage = "Error: couldn't load settings/themes.json.";
  50. } else {
  51. errorMessage = "No themes found in settings/themes.json.";
  52. }
  53. d3.select("#loading-bars").remove();
  54. d3.select("#loading-message").html(errorMessage);
  55. if (err) {
  56. throw err;
  57. }
  58. return;
  59. }
  60. for (var key in themes) {
  61. themes[key] = $.extend({}, themes.default, themes[key]);
  62. }
  63. preloadImages(themes);
  64. });
  65. function submitted() {
  66. d3.event.preventDefault();
  67. var theme = preview.theme(),
  68. caption = preview.caption(),
  69. citation = preview.citation(),
  70. label = preview.label(),
  71. selection = preview.selection(),
  72. file = preview.file();
  73. // combine timestamp and caption for easy-to-scan filenames
  74. identifier = timestamp() + preview.caption().replace(/\s+/g, '_').replace(/\'|\"|\.|\?|\!/g, '').toLowerCase().slice(0, 20);
  75. if (!file) {
  76. d3.select("#row-audio").classed("error", true);
  77. return setClass("error", "No audio file selected.");
  78. }
  79. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  80. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  81. }
  82. if (!theme || !theme.width || !theme.height) {
  83. return setClass("error", "No valid theme detected.");
  84. }
  85. if (theme.labelText) {
  86. label = theme.labelText;
  87. }
  88. video.kill();
  89. audio.pause();
  90. var formData = new FormData();
  91. formData.append("audio", file);
  92. if (selection.start || selection.end) {
  93. formData.append("start", selection.start);
  94. formData.append("end", selection.end);
  95. }
  96. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  97. formData.append("caption", caption);
  98. formData.append("citation", citation);
  99. formData.append("label", label);
  100. formData.append("identifier", identifier);
  101. setClass("loading");
  102. d3.select("#loading-message").text("Uploading audio...");
  103. $.ajax({
  104. url: "/submit/",
  105. type: "POST",
  106. data: formData,
  107. contentType: false,
  108. dataType: "json",
  109. cache: false,
  110. processData: false,
  111. success: function(data){
  112. poll(data.id, 0);
  113. },
  114. error: error
  115. });
  116. }
  117. function poll(id) {
  118. setTimeout(function(){
  119. $.ajax({
  120. url: "/status/" + id + "/",
  121. error: error,
  122. dataType: "json",
  123. success: function(result){
  124. if (result && result.status && result.status === "ready" && result.url) {
  125. video.update(result.url, identifier);
  126. setClass("rendered");
  127. } else if (result.status === "error") {
  128. error(result.error);
  129. } else {
  130. d3.select("#loading-message").text(statusMessage(result));
  131. poll(id);
  132. }
  133. }
  134. });
  135. }, 2500);
  136. }
  137. function error(msg) {
  138. if (msg.responseText) {
  139. msg = msg.responseText;
  140. }
  141. if (typeof msg !== "string") {
  142. msg = JSON.stringify(msg);
  143. }
  144. if (!msg) {
  145. msg = "Unknown error";
  146. }
  147. d3.select("#loading-message").text("Loading...");
  148. setClass("error", msg);
  149. }
  150. // Once images are downloaded, set up listeners
  151. function initialize(err, themesWithImages) {
  152. // Populate themes menu
  153. d3.select("#input-theme")
  154. .on("change", updateTheme)
  155. .selectAll("option")
  156. .data(themesWithImages)
  157. .enter()
  158. .append("option")
  159. .text(function(d){
  160. return d.name;
  161. });
  162. // Get initial theme
  163. d3.select("#input-theme").each(updateTheme);
  164. // Get initial caption (e.g. back button)
  165. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  166. // Get initial citation (e.g. back button)
  167. d3.select("#input-citation").on("change keyup", updateCitation).each(updateCitation);
  168. // Space bar listener for audio play/pause
  169. d3.select(document).on("keypress", function(){
  170. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  171. audio.toggle();
  172. }
  173. });
  174. // Button listeners
  175. d3.selectAll("#play, #pause").on("click", function(){
  176. d3.event.preventDefault();
  177. audio.toggle();
  178. });
  179. d3.select("#restart").on("click", function(){
  180. d3.event.preventDefault();
  181. audio.restart();
  182. });
  183. // If there's an initial piece of audio (e.g. back button) load it
  184. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  185. d3.select("#return").on("click", function(){
  186. d3.event.preventDefault();
  187. video.kill();
  188. setClass(null);
  189. });
  190. d3.select("#submit").on("click", submitted);
  191. }
  192. function updateAudioFile() {
  193. d3.select("#row-audio").classed("error", false);
  194. audio.pause();
  195. video.kill();
  196. // Skip if empty
  197. if (!this.files || !this.files[0]) {
  198. d3.select("#minimap").classed("hidden", true);
  199. preview.file(null);
  200. setClass(null);
  201. return true;
  202. }
  203. d3.select("#loading-message").text("Analyzing...");
  204. setClass("loading");
  205. preview.loadAudio(this.files[0], function(err){
  206. if (err) {
  207. d3.select("#row-audio").classed("error", true);
  208. setClass("error", "Error decoding audio file");
  209. } else {
  210. setClass(null);
  211. }
  212. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  213. });
  214. }
  215. function updateCaption() {
  216. preview.caption(this.value);
  217. }
  218. function updateCitation() {
  219. preview.citation(this.value);
  220. }
  221. function updateLabel() {
  222. preview.label(this.value);
  223. }
  224. function updateTheme() {
  225. var theme_obj = d3.select(this.options[this.selectedIndex]).datum(),
  226. that = this;
  227. // Automatically set the label for themes that have them
  228. preview.theme(theme_obj);
  229. if (theme_obj.labelText) {
  230. preview.label(theme_obj.labelText);
  231. $('#input-label').children().each(function (i, c) {
  232. if (c.value === that.options[that.selectedIndex].value) {
  233. $(c).prop('selected', true);
  234. return false;
  235. }
  236. });
  237. $('#input-label').prop('disabled', true);
  238. }
  239. else {
  240. $('#input-label').prop('disabled', false);
  241. }
  242. }
  243. function preloadImages(themes) {
  244. // preload images
  245. var imageQueue = d3.queue();
  246. d3.entries(themes).forEach(function(theme){
  247. if (!theme.value.name) {
  248. theme.value.name = theme.key;
  249. }
  250. if (theme.key !== "default") {
  251. imageQueue.defer(getImage, theme.value);
  252. }
  253. });
  254. imageQueue.awaitAll(initialize);
  255. function getImage(theme, cb) {
  256. if (!theme.backgroundImage) {
  257. return cb(null, theme);
  258. }
  259. theme.backgroundImageFile = new Image();
  260. theme.backgroundImageFile.onload = function(){
  261. return cb(null, theme);
  262. };
  263. theme.backgroundImageFile.onerror = function(e){
  264. console.warn(e);
  265. return cb(null, theme);
  266. };
  267. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  268. }
  269. }
  270. function setClass(cl, msg) {
  271. d3.select("body").attr("class", cl || null);
  272. d3.select("#error").text(msg || "");
  273. }
  274. function statusMessage(result) {
  275. switch (result.status) {
  276. case "queued":
  277. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  278. case "audio-download":
  279. return "Downloading audio for processing";
  280. case "trim":
  281. return "Trimming audio";
  282. case "probing":
  283. return "Probing audio file";
  284. case "waveform":
  285. return "Analyzing waveform";
  286. case "renderer":
  287. return "Initializing renderer";
  288. case "frames":
  289. var msg = "Generating frames";
  290. if (result.numFrames) {
  291. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  292. }
  293. return msg;
  294. case "combine":
  295. return "Combining frames with audio";
  296. case "ready":
  297. return "Cleaning up";
  298. default:
  299. return JSON.stringify(result);
  300. }
  301. }